我有一个每分钟执行一次的 cron 作业。但我发现它运行了多次。我正在寻找一种方法来检查进程是否仍在运行,然后不要启动一个新进程,或者在启动一个新进程之前终止已经运行的进程。
最佳答案
如果你想要php解决方案,简单的方法是创建一个锁定文件,每次执行脚本时,检查文件是否存在然后退出脚本,如果不存在则让脚本结束。但我认为在 cron 指令中使用 flock 会更好;)
<?php
$filename = "myscript.lock";
$lifelimit = 120; // in Second lifetime to prevent errors
/* check lifetime of file if exist */
if(file_exists($filename)){
$lifetime = time() - filemtime($filename);
}else{
$lifetime = 0;
}
/* check if file exist or if file is too old */
if(!file_exists($filename) || $lifetime > $lifelimit){
if($lifetime > $lifelimit){
unlink($filename); //Suppress if exist and too old
}
$file=fopen($filename, "w+"); // Create lockfile
if($file == false){
die("file didn't create, check permissions");
}
/* Your process */
unlink($filename); //Suppress lock file after your process
}else{
exit(); // Process already in progress
}
关于php - 检查 php 文件命令是否已经在 cron 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32456985/