How to prevent PHP script running more than once?(如何防止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脚本多次运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止PHP脚本多次运行?


基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01