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 中查看页面? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01