PHP - Restrict cron job overlap with flock()

蹲街弑〆低调 提交于 2020-01-03 01:47:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26124513/php-restrict-cron-job-overlap-with-flock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!