Toni Toni - 8 months ago 55
PHP Question

Check if a php file command is already running on cron

I have a cron job that executes every minutes. But I discovered thats it's running multiple times. I'm looking for a way to check if the process is still running then don't start a new one, or terminate the already running process before starting a new one.

Fky Fky

If you want the php solution, the simple way is to create a lock file, each time script is executed , check if file exist then exit script, if not let script go to end. But i think it's better to use flock in cron instruction ;)

    $filename = "myscript.lock";
    $lifelimit = 120; // in Second lifetime to prevent errors
    /* check lifetime of file if exist */
       $lifetime = time() - filemtime($filename);
       $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 
        exit(); // Process already in progress