How to determine if a script (cron) is running?

Good afternoon.

I run the script with cron every 5 minutes. Is it possible to determine if a script is still running or not?

It’s just that if the script is already running, it’s not advisable to run it in duplicate..


Answer 1, authority 100%

One of the verification options is to use the file’s system lock. In this case, even if the process dies, the lock will be released and the subsequent launch will not be blocked.

function lock($name) {
    $lock = sys_get_temp_dir()."/$name.lock";
    $aborted = file_exists($lock) ? filemtime($lock) : null;
    $fp = fopen($lock, 'w');
    if (!flock($fp, LOCK_EX|LOCK_NB)) {
        //    ,    
        return false;
    }
    //   
    //        -  
    if ($aborted) {
        error_log(sprintf("  %s    %s", $name, date('c', $aborted)));
    }
    //      
    //   callback,   ,   
    //     ,   
    register_shutdown_function(function() use ($fp, $lock) {
        flock($fp, LOCK_UN);
        fclose($fp);
        unlink($lock);
    });
    return true;
}

Or you can store the process PID in a file, as suggested by @avp. The difference between these approaches will be visible only on Windows.


Answer 2, authority 50%

It is possible for the script to create a file, a flag file – if there is a file, then we do not work.
And at the end of the script cron, delete the file.

Leave a reply

Please enter your comment!
Please enter your name here