Search code examples
phplinuxcroncentos

How to prevent PHP script running more than once?


Currently, I tried to prevent an onlytask.php script from running more than once:

$fp = fopen("/tmp/"."onlyme.lock", "a+");
if (flock($fp, LOCK_EX | LOCK_NB)) {
  echo "task started\n";
  //
    while (true) {
      // do something lengthy
      sleep(10);
    }
  //
  flock($fp, LOCK_UN);
} else {
  echo "task already running\n";
}
fclose($fp);

and there is a cron job to execute the above script every minute:

* * * * * php /usr/local/src/onlytask.php

It works for a while. After a few day, when I do:

ps auxwww | grep onlytask

I found that there are two instances running! Not three or more, not one. I killed one of the instances. After a few days, there are two instances again.

What's wrong in the code? Are there other alternatives to limit only one instance of the onlytask.php is running?

p.s. my /tmp/ folder is not cleaned up. ls -al /tmp/*.lock show the lock file was created in day one:

-rw-r--r--  1 root root    0 Dec  4 04:03 onlyme.lock

Solution

  • Now I check whether the process is running by ps and warp the php script by a bash script:

     #!/bin/bash
    
     PIDS=`ps aux | grep onlytask.php | grep -v grep`
     if [ -z "$PIDS" ]; then
         echo "Starting onlytask.php ..."
         php /usr/local/src/onlytask.php >> /var/log/onlytask.log &
     else
         echo "onlytask.php already running."
     fi
    

    and run the bash script by cron every minute.