如何阻止 cron 作业执行(如果它已经在运行)

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

我有一个 php 脚本,我在 CentOS 上每 10 分钟通过 cron 执行一次这个脚本.

I have one php script, and I am executing this script via cron every 10 minutes on CentOS.

问题在于,如果 cron 作业将花费 10 分钟以上,那么同一 cron 作业的另一个实例将启动.

The problem is that if the cron job will take more than 10 minutes, then another instance of the same cron job will start.

我尝试了一个技巧,那就是:

I tried one trick, that is:

  1. 使用php代码(与pid文件相同)创建了一个锁定文件,当cron 作业开始了.
  2. 在作业完成后使用 php 代码删除了锁定文件.
  3. 当任何新的 cron 作业开始执行脚本时,我检查是否锁定文件存在,如果存在,则中止脚本.

但是可能会出现一个问题,即锁定文件由于任何原因没有被脚本删除或删除.cron 将永远不会再次启动.

But there can be one problem that, when the lock file is not deleted or removed by script because of any reason. The cron will never start again.

如果 cron 作业已经在运行,有什么办法可以再次停止它的执行,使用 Linux 命令或类似的命令吗?

Is there any way I can stop the execution of a cron job again if it is already running, with Linux commands or similar to this?

推荐答案

建议锁定正是为此目的而设计的.

Advisory locking is made for exactly this purpose.

您可以使用 flock() 完成咨询锁定.只需将该函数应用于先前打开的锁定文件,即可确定是否有其他脚本对其进行了锁定.

You can accomplish advisory locking with flock(). Simply apply the function to a previously opened lock file to determine if another script has a lock on it.

$f = fopen('lock', 'w') or die ('Cannot create lock file');
if (flock($f, LOCK_EX | LOCK_NB)) {
    // yay
}

在本例中,我添加了 LOCK_NB 以防止下一个脚本等待第一个脚本完成.由于您使用的是 cron,因此总会有下一个脚本.

In this case I'm adding LOCK_NB to prevent the next script from waiting until the first has finished. Since you're using cron there will always be a next script.

如果当前脚本提前终止,任何文件锁都会被操作系统释放.

If the current script prematurely terminates, any file locks will get released by the OS.

相关文章