Toni Toni - 2 months ago 18
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
Answer

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 ;)

<?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
    }