PHP - Preventing collision in Cron - File lock safe?

前端 未结 3 997
说谎
说谎 2020-12-13 15:25

I\'m trying to find a safe way to prevent a cron job collision (ie. prevent it from running if another instance is already running).

Some options I\'ve found recomme

3条回答
  •  一向
    一向 (楼主)
    2020-12-13 15:51

    This sample was taken at http://php.net/flock and changed a little and this is a correct way to do what you want:

    $fp = fopen("/path/to/lock/file", "w+");
    if (flock($fp, LOCK_EX | LOCK_NB)) { // do an exclusive lock
      // do the work
      flock($fp, LOCK_UN); // release the lock
    } else {
      echo "Couldn't get the lock!";
    }
    fclose($fp);
    

    Do not use locations such as /tmp or /var/tmp as they could be cleaned up at any time by your system, thus messing with your lock as per the docs:

    Programs must not assume that any files or directories in /tmp are preserved between invocations of the program.

    https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch03s18.html https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch05s15.html

    Do use a location that is under your control.

    Credits:

    • Michaël Perrin - for proposing to use w+ instead of r+

提交回复
热议问题