0

I am using a crontab that executes a PHP file. I want to implement the flock() command to help prevent duplicate crontabs from running at one time. If I have:

* * * * * php /var/www/html/welcome.php

How can i add this flock() command? Thanks!

scrowler
  • 24,273
  • 9
  • 60
  • 92
user3647894
  • 559
  • 1
  • 4
  • 28

2 Answers2

2

Try this:

$fh = fopen('mutex.txt','r');  // Any convenient file (MUTual EXclusion)
flock($fh, LOCK_EX);       // get exclusive lock. Will block until lock is acquired

// Do your exclusive stuff...

flock($fh, LOCK_UN);      // release lock
fclose($fh);              // close Mutex file.
  • thank you for the response! now is this in my welcome.php file? – user3647894 May 23 '14 at 18:22
  • Hi thanks for this answer. However I have to add 'r' like : $fh = fopen('mutex.txt', 'r'); Because I got : fopen() expects at least 2 parameters, 1 given is that normal ? However it's work great I try to launch a seconds php (cli) and the script do not execute (wait) as expected. – Anyone_ph Jun 22 '15 at 16:06
0

For complete your answer and as you use a crontab every minute, you may encounter a problem :

If for any reason, your script lack to finish in 1 minute his job or the script fail somewhere and does not remove the lock (stuck inside a 'while'...), the next crontab will start and stay in your process list until the previous remove his lock, and so on...

A better approach would be :

$fh = fopen('/path/to/mutex.txt', 'r');  //Any convenient file (MUTual EXclusion)

  if(!flock($fh, LOCK_EX | LOCK_NB)) //Exit if lock still active
   exit(-1);

   //Your code here

  flock($fh, LOCK_UN);      //release lock
  fclose($fh);              //close Mutex file.

And that will avoid any stack of process php

Anyone_ph
  • 616
  • 6
  • 15