php - 检查 php 文件命令是否已经在 cron 上运行

标签 php process cron

我有一个每分钟执行一次的 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/

相关文章:

php - 警告 : Assignment in condition

php - preg_match() : Compilation failed: missing ) at offset 14 after i upgraded to php7

php - 访问另一个php文件中的类的属性和方法

ruby 创建进程和读取输出

linux - 如何在 linux 中获取特定进程名称的进程 ID?

PHP mysqli 搜索多个表

c++ - 检测 C++/Win32 中的进程崩溃

c# - 当*任何*进程启动时得到通知,然后卡住/暂停/挂起它

linux - 这个 Cron 的时间表是什么?

python - 如何使用 cron 在 Raspberry Pi 上自动化 Python 程序?