PHP - 限制cron作业与flock() [英] PHP - Restrict cron job overlap with flock()
问题描述
我有一个php脚本来处理和创建大量的图像,每5分钟使用cron作业运行。我想能够限制这一点,所以它只能运行一次,而不是重叠,如果每次运行需要超过5分钟。
flock()
似乎是实现这个的最好方法,但我很难理解我应该如何添加这到我现有的脚本。我的cron作业设置为运行以下文件 -
images.php:
$ array = array(Volvo,BMW,Toyota,Audi,Ford,Alfa,Porsche,Mercedes);
foreach($ array as $ car){
generateImageCustomFunction($ car);
}
我想使用非阻塞锁, p>
$ fp = fopen('/ tmp / lock.txt','r +');
if(!flock($ fp,LOCK_EX | LOCK_NB)){
echo'无法获取锁';
exit(-1);
}
fclose($ fp);
`lock.txt'只是一个存储/表示锁的纯文本文件,实际文件我试图运行 - 在这种情况下 images.php ?
也在哪里我真的坚持我现有的代码在
您的代码在这里:
$ fp = fopen('/ tmp / lock.txt','w');
if(!flock($ fp,LOCK_EX | LOCK_NB)){
echo'无法获取锁'
exit(-1);
}
//您的代码
sleep(5);
fclose($ fp);
lock.txt
您需要对此文件的写访问权限才能创建它。并为您的锁定文件使用唯一的名称,因此不会干扰其他进程。
I have a php script that processes and creates lots of images which is being run every 5 minutes using cron job. I want to be able to limit this so it can only run once at a time and not overlap if each run takes longer than 5 minutes.
flock()
seems like the best way to achieve this but i am struggling to understand how exactly i should add this into my existing script. My cron job is setup to run the following file -
images.php:
$array=array("Volvo","BMW","Toyota","Audi","Ford","Alfa","Porsche","Mercedes");
foreach ($array as $car) {
generateImageCustomFunction($car);
}
I want to use a non blocking lock so based on the examples:
$fp = fopen('/tmp/lock.txt', 'r+');
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock';
exit(-1);
}
fclose($fp);
Is `lock.txt' just a plain text file that stores/indicates the lock or is that the actual file i'm trying to run - in this case images.php?
Also where about do i actually stick my existing code in the above?
Your Code goes here:
$fp = fopen('/tmp/lock.txt', 'w');
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock';
exit(-1);
}
// YOUR CODE HERE
sleep(5);
fclose($fp);
lock.txt
just holds your lock. You need write access to this file to create it in the first place. And use a unique name for your locking file, so it doesn't interfere with other processes.
这篇关于PHP - 限制cron作业与flock()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!