user2403357
user2403357

Reputation:

Timer mysql php check

It's bugging me for a day now and I really cant find out, I have a basic login/register page, and when registering, a timestamp is stored in the mysql database(table timer, column cooldown):

$settime = mysql_query("INSERT INTO `timer` (`cooldown`) VALUES(0)") or die(mysql_error());

What I want to do now (I'm creating a browser mmorpg), Is when I do a specific POST request, I want a timer in my database to go off. This timer should be 1 minute, and also be shown for users, like: <?php echo $timer['cooldown']; ?> Whenever the timer is = 0, I can do a specific function again, and the timer will be set to 60 seconds again.

Sorry for the lack of knowledge but I can't find out anywhere how to do this.

Upvotes: 0

Views: 1386

Answers (1)

chiborg
chiborg

Reputation: 28134

What you're trying to do here - a background job - goes against the web development principle of a request-response cycle in the shared-nothing environment of PHP. But there are several ways to break up the rigid cycle:

  • If you just need to do some DB updates after 1 minute, you can use MySQL events: http://dev.mysql.com/doc/refman/5.1/en/events.html
  • If the function you want to call is not running too long, you can check on every user request if there are entries in the timer table that are older than 1 minute.
  • Create a PHP script that is called by a cron job every minute. It checks if there are unhandled items in the timer table and does something with them.
  • Create a PHP daemon script that wakes up every minute to check.
  • If you need to change something on the user page after 1 minute, doing the PHP script call client-side with a JavaScript timeout and AJAX or websockets is the better option.

For displaying the countdown to the user, you have to use JavaScript. If you are using the server-side timer, you can use it just for display purposes, hiding the countdown when it's finished. To work around the "user opens new page before timout is finished" problem, put the data for the remaining seconds in an HTML data attribute where your JavaScript code can read it.

Upvotes: 1

Related Questions