Search code examples
phplinuxprocessjobssystem

How to check php job instance


In my system, I've scheduled a PHP job to run each minute.

Now I want that if 1 instance of this job is running and it takes more than 1 min, the new instance that starts after every minute checks if any previous instance is working and there is any previous instance running, the new one kills itself...I was trying the system() commands but cant figure it out.

Any sugestions


Solution

  • Use exclusive file lock on a lock file. As soon as process ends it execution, the lock is automatically released.

    <?php    
    $fp = fopen("/var/tmp/your.lock", "w");
    if (!flock($fp, LOCK_EX|LOCK_NB)) { // try to get exclusive lock, non-blocking
        die("Another instance is running");
    } 
    
    [... continue with the script ...]
    

    See: http://www.php.net/manual/en/function.flock.php