开发者

Running scheduled jobs

I want to call a function exactly 30 mins after a user submits a form. I was using javascript setTimeOut() function but that clears of the timer at page ref开发者_如何学Pythonresh or browser close. No matter what (whether the browser is closed or refreshed), I want to call the function exactly after 30 mins & I also want to display the remaining time to the 30 mins as well as.

I looked at Cron jobs but my understanding is that PHP can not invoke a cron job directly.

Can anyone tell me what will be the best approach to do this??


  1. The at command and associated atd daemon can schedule things to be executed at an arbitrary time in the future. You would likely have to write a specialized php script to pass to at. You can pass extra arguments to it in order to know which user submitted the form, etc. This code would, of course, be executed on the server. The PHP code would store the results in the database (or similar global data store).
  2. To display how much time would be left to the user, I would store the time in the session or database. Remember that the server time will be different than what is on the user's computer, so it's best to do any difference calculations on the server, not in JavaScript.
  3. A setTimeout() call can still be used to assure the browser is redirected to a page (or load it via AJAX, etc) to view the results at the appropriate time (assuming the user is on your site when the event occurs). Keep calling the setTimeout() on every page load to the correct time based on the time in the session.

Keep in mind that the PHP code in step #1 will take time to execute and such, so you may want to add a small delay to #3 to make sure the results are available, as well as appropriate error handling should the results be unavailable for other reasons.


I voted for @wuputah method and agree that it is best, but if you are unable to access step #1 of his (on shared hosting, etc) then you can set the timestamp in a database and set up a cron job to run every 1 minute which checks the database for "expired" times without a "processed" flag...and then do your procedure to that data (and mark the DB entry as "processed" so it does not get executed on the next cycle).

+---------------------------------------------+
| RECORD ID | TIMESTAMP           | PROCESSED |
+---------------------------------------------+
|   1       | 2010-02-06 15:27:10 | yes       |
|   2       | 2010-02-06 15:47:10 | no        |
|   3       | 2010-02-06 15:49:10 | no        |
+---------------------------------------------+
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜