如何防止 cron 作业执行,如果它已经在运行

2022-01-13 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.

相关文章