开发者

Perform query when timer reaches zero

开发者 https://www.devze.com 2023-02-10 10:41 出处:网络
The idea is pretty simple: Where the timer is made in Javascript, when it reaches zero it performs a query in PHP that alters the database value to add 1.

The idea is pretty simple:

Where the timer is made in Javascript, when it reaches zero it performs a query in PHP that alters the database value to add 1.

The problem is that the timer in question must not be reset with page refresh, just like any browser based game, when you build a new facility.

This is for a school game project, in which you click "Build" and dep开发者_如何学Pythonending on that facility's level it would take X time to upgrade it to a new level, showing a timer that tells the user how much time left until the upgrade is done.

I'm really sorry if the solution is somewhere here, but I swear to god I've searched everywhere but I could not get a decent methodology to do this.


Do not rely on frontend script to do this, instead schedule a task in the backend. some ways to do it. If the load and users are less, and timer value is not very high. Put Sleep(10) ( for 10 seconds ) in your script.and call it through your javascript, it will execute the query after 10 seconds :) . And will work even if the browser is closed or page is refrehsed

Php script :

<?php

  $timer = $_REQUEST['timer'];
  $timer = intval($timer);
   sleep($timer); // sleep for some seconds
   ....rest of the stuff..

 ?>

However for heavy use, and large intervals like 15 minutes etc, you can immediately store some information and triggering time in a database, and later on process them with a cron ( scheduled task ) in the backend


store the time of last update in the database and make the page check once every 5 minutes or so


That can be tricky, because you will always have latency so this won't be accurate.

But what you can do, is letting PHP generate a 'remaining time' value when the page refreshes. That is the time since the last write to the database. When the page loads, you can initialize a new timer with a delay of YourDelay - TimeSinceLastWrite. After that you start the regular timer that will just have YourDelay as an interval.

Another option, and probably more accurate too, is saving the time of the request (AJAX, a assume?) to a cookie. When the page loads, you can check for the cookie and perform the same logic as described above. Only it will be a little more accurate because you do all the timing on the same machine, not having problems with latency or different system clocks.

0

精彩评论

暂无评论...
验证码 换一张
取 消