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

How to prevent PHP script running more than once?(如何防止PHP脚本多次运行?)
本文介绍了如何防止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.

这篇关于如何防止PHP脚本多次运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)