如何防止PHP脚本运行不止一次? [英] How to prevent PHP script running more than once?

查看:207
本文介绍了如何防止PHP脚本运行不止一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  $ fp = fopen(/ tmp /。onlyme.lock,a +); 
if(flock($ fp,LOCK_EX | LOCK_NB)){
echotask started\\\
;
//
while(true){
//做长度
sleep(10);
}
//
flock($ fp,LOCK_UN);
} else {
echotask already running\\\
;
}
fclose($ fp);

,每分钟都有一个cron作业来执行上述脚本:

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

它工作一段时间。几天后,当我做:

  ps auxwww | grep onlytask 

我发现有两个实例运行!不是三个或更多,不是一个。我杀了一个实例。几天后,再次有两个实例。



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



p.s。我的 / tmp / 文件夹未清除。 ls -al / tmp / *。lock 显示锁定文件是在第一天创建的:

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


<现在我检查进程是否由 ps 运行,并通过<$ c $>改变php脚本c> bash 脚本:

 #!/ bin / bash 

PIDS =`ps aux | grep onlytask.php | grep -v grep`
if [-z$ PIDS];然后
echoStarting onlytask.php ...
php /usr/local/src/onlytask.php>> /var/log/onlytask.log&
else
echoonlytask.php already running。
fi

并运行 bash cron 的脚本。


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\n";
  //
    while (true) {
      // do something lengthy
      sleep(10);
    }
  //
  flock($fp, LOCK_UN);
} else {
  echo "task already running\n";
}
fclose($fp);

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.

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

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

解决方案

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

and run the bash script by cron every minute.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆