开发者

PHP run scripts at dynamic times? Job for cron or no?

I need to run scripts at dynamic times (coinciding with a datetime in a database). Any ideas how to accomplish this?

Example:

开发者_StackOverflow

Database says tomorrow at noon in 1 in a datetime field, then i want to run the script tomorrow at noon.


A very simple approach is to have a cron-job call a PHP script every 1 minute, and have it check the database for things that need done. If something needs done NOW(), then do it and remove from database.

You need to consider things like locking, process stacking, multiple processes, etc... to make this robust. But if your need is simple, this is a simple way to make it work.

Add this to crontab:

* * * * *   /usr/bin/php /path/to/my/script.php

And in /path/to/my/script.php

<?php
$ts = time();

// Run for up to 50 seconds
while($ts + 50 > time())
{
   ... SELECT id, job_stuff FROM JobTable WHERE JobDate <= NOW() ...

   process job

   ... DELETE job_stuff FROM JobTable WHERE id = ...

   sleep(5);       
} 

Note, this is not robust. A robust script would grab a record while locked, update it to a "processing" status, process it, and update it to a "complete" status. This means that multiple processes could work at this same time (even if accidental) and not duplicate jobs. Also, this means that a single failure would not stop the train.


Another way might have a script that checks the database at reguiar intervals and once it sees a new job create the cron job for that script. You'd obviously need some way to ensure that your processes are updated once they are inserted into the relevant crontab.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜