Run PHP script automatically without user input at certain conditions?
October 27, 2010 11:11 AM Subscribe
How do I make a PHP script run only once if certain conditions are met, without involving the users?
I'm writing an online e-game with PHP. I need to figure out how to run the "tick.php" script automatically once a certain condition— a certain amount of elapsed time since a MySQL field— is met. This script must only be run once, at that time, and not be dependent on any kind of user input. Currently, I have a button on the admin control panel that runs it, but obviously this will only run the script manually. The script has a lot of output which I would prefer to save somewhere for later access, although this is not completely necessary. I'm not a very good programmer so I assume there are lots of other things that I'm not considering. The script can take up to a minute to run.
Here some solutions I've considered and rejected:
1. Run the script on page load if the condition is met. Not a strong enough way to prevent the script from being run twice concurrently (i.e., if users load a page at the same time), no way to save the output (?), the page load will be delayed if the script is taking a while and if the user quits the page the script will be aborted, if no user is looking at pages at the time then the script won't run.
2. Cron job. Cron job can't check for the condition. I could run it more often than the condition and let the script run only if the condition is set, but this seems wasteful. I'm using Dreamhost for the project and I don't want to have a cron job running every minute.
3. Call the script as AJAX. Many of the same problems as #1.
4. Use PHP's internal tick functions. Not keyed to time, many of the same problems as #1.
5. Have dedicated team of game admins run ticks manually when the time is up. Haha, right.
Any suggestions are welcome. I know this is possible; I just don't know how to do it and Google seems to come up short.
posted by Electrius to computers & internet (10 answers total)
It might also be a good idea to see if you can rewrite the script itself to not have any side-effects in the case that it is run twice.
Apart from that - the cron job every minute will not be wasteful, as long as the core of the script gets only executed when necessary. A small script and a single database query per minute is completely negligible in terms of server load.
posted by uncle harold at 11:28 AM on October 27, 2010