Reputation: 4111
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?
Upvotes: 2
Views: 4207
Reputation: 3679
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.
Upvotes: 2