简体   繁体   English

Cron中同时运行多个PHP脚本

[英]Multiple PHP scripts run at same time in Cron

I have a crontab that looks like the following 我有一个crontab,如下所示

* 22 * * * php /var/www/domain1/cron.php
* 22 * * * php /var/www/domain2/cron.php
* 22 * * * php /var/www/domain3/cron.php
* 22 * * * php /var/www/domain4/cron.php
...

However the scrips shown above seems to mess up and run op to a hundred times each! 但是,上面显示的脚本似乎弄乱了,每次运行多达100次! Im not sure why this happens, but since they are all set to start at the same time i would try and change this. 我不确定为什么会这样,但是由于它们都准备在同一时间启动,因此我将尝试更改此设置。 It should be said that if i run each cron file manually i see no such behavior and get the expected behavior. 应该说,如果我手动运行每个cron文件,我看不到任何此类行为并获得预期的行为。

Can i somehow let cron only run one line at a time ? 我能以某种方式让cron一次只运行一行吗? So that when domain1/cron.php is run it will not run domain2/cron.php before domain1/cron.php has finished? 这样,当domain1 / cron.php运行时,它将不会在domain1 / cron.php完成之前运行domain2 / cron.php吗?

I cannot change the time for them, since i cannot be sure when each one finishes. 我不能为他们更改时间,因为我不确定每个完成的时间。 On one domain it might take 3 seconds while on another it might take 30 minutes. 在一个域上可能需要3秒,而在另一个域上可能需要30分钟。

Put them all on a single command line, so they will be run sequentially. 将它们全部放在一个命令行中,因此它们将按顺序运行。

* 22 * * * php /var/www/domain1/cron.php; php /var/www/domain2/cron.php; php /var/www/domain3/cron.php; php /var/www/domain4/cron.php

But since this cron job runs every minute during hour 22, you'll still get overlap if they take more than a minute. 但是,由于此cron作业在22小时内每分钟运行一次,因此,如果花费超过一分钟,您仍然会出现重叠。

If you have the root permission you can try this way. 如果您具有root权限,则可以尝试这种方式。

* 22 * * * /root/sbin/allDomainsCron.sh

Where allDomainsCron.sh contains your domains cron.php one by one: 在allDomainsCron.sh包含您的域cron.php的一个一个的地方:

#!bin/bash
php /var/www/domain1/cron.php
php /var/www/domain2/cron.php
php /var/www/domain3/cron.php
php /var/www/domain4/cron.php
...

So you can ensure that only one cron.php run at a time. 因此,您可以确保一次只运行一个cron.php。

If you would run the script once a day at 22:00 this code will do the work: 如果您每天在22:00运行一次脚本,则此代码可以完成工作:

0 22 * * * /root/sbin/allDomainsCron.sh

No, a crontab does not offer you in-order execution. 不可以,crontab不能按顺序执行。 It's also unreliable to use cron this way. 以这种方式使用cron也不可靠。 What you're probably wanting instead is an actual queue or job manager that can effectively control the outcome and flow of your desired job execution much more reliably than crontabs can. 相反,您可能想要的是一个实际的队列或作业管理器,它可以比crontabs更可靠地有效控制所需作业执行的结果和流程。 You could checkout something like RabbitMQ, ZeroMQ, or Gearman for this. 您可以为此签出RabbitMQ,ZeroMQ或Gearman之类的东西。 Or if you're using AWS, SQS is a good start. 或者,如果您使用的是AWS,则SQS是一个好的开始。

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

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