PHP - 在 Cron 中防止碰撞 - 文件锁定安全吗?

2022-01-03 00:00:00 cron collision php

我正在尝试寻找一种安全的方法来防止 cron 作业冲突(即,如果另一个实例已经在运行,则阻止它运行).

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).

一些我发现推荐的选项 对文件使用锁.

这真的是一个安全的选择吗?例如,如果脚本死了会发生什么?锁会保留吗?

Is that really a safe option? What would happen if the script dies for example? Will the lock remain?

还有其他方法可以做到这一点吗?

Are there other ways of doing this?

推荐答案

此示例取自 http://php.net/flock 并稍作改动,这是一个正确的方式来做你想做的事:

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);

不要使用诸如 /tmp/var/tmp 之类的位置,因为它们可能会被您的系统随时清除,因此根据文档弄乱了您的锁:

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:

程序不得假定/tmp 中的任何文件或目录在程序调用之间都保留.

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.htmlhttps://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch05s15.html

务必使用您可以控制的位置.

Do use a location that is under your control.

学分:

  • Michaël Perrin - 提议使用 w+ 而不是 r+
  • Michaël Perrin - for proposing to use w+ instead of r+

相关文章