[英]Improve prevent php script run twice (with cronjobs)
I'm like to improve script below, or maybe know if exist a better way to rewrite to better results.我想改进下面的脚本,或者可能知道是否存在更好的重写方法以获得更好的结果。
I use this on two files cron1.php and cron2.php executed every 5 seconds and need to prevent running twice.我在两个文件 cron1.php 和 cron2.php 上使用它,每 5 秒执行一次,并且需要防止运行两次。
Script execution time depends of filesize, most of the time took around 2 seconds, but for huge files can take 25/30 seconds, for this i need to stop execution.脚本执行时间取决于文件大小,大部分时间大约需要 2 秒,但对于大文件可能需要 25/30 秒,为此我需要停止执行。
I'm on right way?我走对了吗? Any suggestion to improve?
有什么改进的建议吗?
$fp = fopen("cron.lock", "a+");
if (flock($fp, LOCK_EX | LOCK_NB))
{
echo "task started\n";
// Here is my long script
// Cron run every 5 seconds
sleep(2);
flock($fp, LOCK_UN);
}
else
{
echo "task already running\n";
exit;
}
fclose($fp);
I generally do a file operation like dumping the getmypid
in the lock file.我通常会执行文件操作,例如将
getmypid
转储到锁定文件中。 So externally I can know which pid has locked it.所以在外部我可以知道哪个 pid 锁定了它。 In some debugging cases, that is helpful.
在某些调试情况下,这很有帮助。 Finally,
unlink
the lock file when you are done.最后,完成后
unlink
锁定文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.