2014-05-23 01:54
浏览 176


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!

图片转代码服务由CSDN问答提供 功能建议

我正在使用执行PHP文件的crontab。 我想实现flock()命令来帮助防止重复的crontabs一次运行。 如果我有:

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


如何 我可以添加这个flock()命令吗? 谢谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsp1836 2014-05-23 02:15

    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.
    打赏 评论
  • dongya9904 2015-06-24 12:28

    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
       //Your code here
      flock($fh, LOCK_UN);      //release lock
      fclose($fh);              //close Mutex file.

    And that will avoid any stack of process php

    打赏 评论

相关推荐 更多相似问题