How to detect whether a PHP script is already running?

后端 未结 9 1420
借酒劲吻你
借酒劲吻你 2021-01-31 11:26

I have a cron script that executes a PHP script every 10 minutes. The script checks a queue and processes the data in the queue. Sometimes the queue has enough data to last ov

9条回答
  •  情深已故
    2021-01-31 11:55

    This worked for me. Set a database record with a lock flag and a time stamp. My script should complete well within 15min so added that as a last locked feild to check:

           $lockresult = mysql_query("
           SELECT *
           FROM queue_locks
           WHERE `lastlocked` > DATE_SUB(NOW() , INTERVAL 15 MINUTE)    
           AND `locked` = 'yes'
           AND `queid` = '1'
           LIMIT 1
            "); 
    $LockedRowCount = mysql_num_rows($lockresult);
    
    if($LockedRowCount>0){
        echo "this script is locked, try again later";
        exit;   
    }else{
    //Set the DB record to locked and carry on son
    $result = mysql_query("
                UPDATE `queue_locks` SET `locked` = 'yes', `lastlocked` = CURRENT_TIMESTAMP WHERE `queid` = 1;
                ");
    
    }
    

    Then unlock it at the end of the script:

        $result = mysql_query("UPDATE `queue_locks` SET `locked` = 'no' WHERE `queid` = 1;");
    

提交回复
热议问题