PHP在动态时运行脚本? 为cron工作还是不工作?

PHP在动态时运行脚本? 为cron工作还是不工作?

问题描述:

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

Example:

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

我需要在动态时间运行脚本(与数据库中的日期时间一致)。 任何想法如何实现这一点? p>

示例: p>

数据库说明天中午1点在日期时间字段中,然后我想运行脚本 明天中午。 p> div>

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.