Possible Duplicate:
Is there a function similar to setTimeout() (JavaScript) for PHP?
Is there any way to do a timeout in PHP? Something similar to setTimeout() in Javascript. I want to insert data in database after 5 minutes.
Edit: Also. It will do another things after 5 minutes. A function will be executed. Then, the approach shouldn't be with the database. A hang is undesirable
The php sleep()
function is the way to go. More details in this thread. In your case the code might be:
<?
sleep(300); // Or 'sleep(5*60);' to make it more readable.
echo 'Do something!';
?>
You'll need to use something like a cron job or task scheduler depending on where you are hosted. PHP is not event driven.
You can use AJAX to save data with the javascript setTimeout.
Im not sure why you need this but you can use
sleep(300);
For more http://php.net/manual/en/function.sleep.php
But I would use a more elegant solution, again this is dependant on what you can or cannot do.
I would store the data in a temporary file. Then use cron to run a script every five minutes to check weather or not a data file exists. If it does, take the file and insert into the database.
If the database does not already have a CURRENT_TIMESTAMP
field, add one. Then, insert the row immediately but set that CURRENT_TIMESTAMP
field to DATE_ADD(NOW(),INTERVAL 5 MINUTE)
.
Then, in whatever code you have SELECT
ing from this table, include WHERE ts <= NOW()
(where ts
is the name of your CURRENT_TIMESTAMP
field)
I use this technique in one of my Cron scripts to simulate it running non-stop when actually it's running once every 15 minutes, by using a random interval between 0 and 15 minutes, and it works really well.
Like others said, there is no "clean" way. You better use a cron job or scheduler-like utility provided by the environment in which you are hosted. And I strongly advise you not to use sleep()
.
An alternative would be the one of completely changing your approach. Why don't you put the data in the DB immediately, but give it a different "meaning" after 5 minutes?
e.g. you post a new row with a timestamp. When you read, you filter out all the rows that have been inserted after 5 minutes ago.