如何防止PHP脚本多次运行?

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

目前,我试图阻止 onlytask.php 脚本多次运行:

Currently, I tried to prevent an onlytask.php script from running more than once:

$fp = fopen("/tmp/"."onlyme.lock", "a+");
if (flock($fp, LOCK_EX | LOCK_NB)) {
  echo "task started
";
  //
    while (true) {
      // do something lengthy
      sleep(10);
    }
  //
  flock($fp, LOCK_UN);
} else {
  echo "task already running
";
}
fclose($fp);

并且每分钟都有一个cron作业来执行上面的脚本:

and there is a cron job to execute the above script every minute:

* * * * * php /usr/local/src/onlytask.php

它可以工作一段时间.几天后,当我这样做时:

It works for a while. After a few day, when I do:

ps auxwww | grep onlytask

我发现有两个实例正在运行!不是三个或更多,不是一个.我杀死了其中一个实例.几天后,又出现了两个实例.

I found that there are two instances running! Not three or more, not one. I killed one of the instances. After a few days, there are two instances again.

代码有什么问题?是否有其他替代方法来限制仅运行 onlytask.php 的一个实例?

What's wrong in the code? Are there other alternatives to limit only one instance of the onlytask.php is running?

附言我的 /tmp/ 文件夹没有清理.ls -al/tmp/*.lock 显示锁文件是在第一天创建的:

p.s. my /tmp/ folder is not cleaned up. ls -al /tmp/*.lock show the lock file was created in day one:

-rw-r--r--  1 root root    0 Dec  4 04:03 onlyme.lock

推荐答案

现在我通过 ps 检查进程是否正在运行,并通过 bash 脚本扭曲 php 脚本:

Now I check whether the process is running by ps and warp the php script by a bash script:

 #!/bin/bash

 PIDS=`ps aux | grep onlytask.php | grep -v grep`
 if [ -z "$PIDS" ]; then
     echo "Starting onlytask.php ..."
     php /usr/local/src/onlytask.php >> /var/log/onlytask.log &
 else
     echo "onlytask.php already running."
 fi

并每分钟通过 cron 运行 bash 脚本.

and run the bash script by cron every minute.

相关文章