PHP进程锁类PHPLock程序代码

作者:袖梨 2022-06-24

程序代码如下

 代码如下 复制代码

//+----------------------------------------------
//|    Usage:
//+----------------------------------------------
//|    public function _initialize(){
//|        import('@.Util.PHPLock');
//|
//|        if(PHPLock::islocked()){
//|            echo "[+] Status: Locked\n";
//|            echo "[+] Exit\n";
//|            exit();
//|        }else{
//|            echo "[+] Status: Unlocked\n";
//|            echo "[-] Locking Now\n";
//|            PHPLock::lock();
//|        }
//|    }
//|
//|    function __destruct(){
//|        if(true === PHPLock::unlock()){
//|            echo "[+] Unlock Success\n";
//|        }
//|    }
//+----------------------------------------------
class PHPLock
{
    const PHPLOCK_TIMEOUT = 1200;
    static private $pid = null;
   
    static public function lock(){
        $key = self::__getKey();
        self::$pid = time();
        F($key, self::$pid);
        return true;
    }
   
    static public function unlock(){
        $key = self::__getKey();
        if(self::$pid){
            F($key, null);
            return true;
        }
        return;
    }
   
    static public function islocked(){
        $key = self::__getKey();
        $time = F($key);

        if(!$time){
            return false;
        }elseif(time() - $time >= self::getTimeout()){
            self::unlock();
            return false;
        }else{
            return true;
        }
    }
   
    static public function getTimeout(){
        $key = str_replace(self::__getKey(), '_Lock', '_TIMEOUT');
        $expire = C($key) ? C($key) : self::PHPLOCK_TIMEOUT;
        return $expire;
    }
   
    static private function __getKey(){
        return (defined('GROUP_NAME') ? GROUP_NAME.'_' : '') . MODULE_NAME . '_' . ACTION_NAME . '_Lock';
    }
}
?>

相关文章

精彩推荐