简体   繁体   English

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

[英]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: 例:

Database says tomorrow at noon in 1 in a datetime field, then i want to run the script tomorrow at noon. 数据库在日期时间字段中的明天中午1点说,那么我想明天中午运行脚本。

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. 一个非常简单的方法是让cron-job每1分钟调用一次PHP脚本,然后让它检查数据库中需要完成的事情。 If something needs done NOW(), then do it and remove from database. 如果需要立即执行NOW(),请执行该操作,然后将其从数据库中删除。

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: 将此添加到crontab中:

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

And in /path/to/my/script.php 并在/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. 另一种方法可能是使用脚本以固定的间隔检查数据库,并且一旦看到新作业,就为该脚本创建cron作业。 You'd obviously need some way to ensure that your processes are updated once they are inserted into the relevant crontab. 显然,您需要某种方法来确保将过程插入相关crontab后对其进行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM