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??
- The
at
command and associatedatd
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 toat
. 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). - 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.
- 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 thesetTimeout()
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 |
+---------------------------------------------+
精彩评论