bonsaicode / filelock
该库用于防止脚本在同一时间运行多次,通过在本地机器上锁定文件提供互斥功能。
1.0.3
2019-08-15 04:40 UTC
Requires
- php: >=7.1.0
This package is auto-updated.
Last update: 2024-09-15 16:11:20 UTC
README
该库用于防止脚本在同一时间运行多次,通过在本地机器上锁定文件提供互斥功能。
场景
1. You run php script A and it acquires the lock having a given name, e.g. "lockA"
2. You try to run script A again while it is still running. It tries to acquire the same "lockA", but cannot because the first script has the lock.
3. After the first script A ends, the "lockA" is released, and then you could run the script again.
当锁被释放时,底层的锁文件将被删除。如果脚本意外终止,锁文件将保留,但下一个脚本可以重新锁定它。
此类适用于单服务器环境,或者当你知道进程将只运行在一个服务器上时。
请不要在多服务器环境中使用,例如自动扩展环境中,可能会动态创建重复的虚拟机。否则,相同的进程可能会同时在多个服务器上运行。因此,我们不使用 sys_get_temp_dir() 作为锁文件目录,因为服务器可能在请求之间发生变化。如果你在具有动态创建虚拟机的多服务器环境中运行,请使用 BonsaiCode\Redis::lockAcquire 和 BonsaiCode\Redis::lockRelease 方法(使用 redis 服务)
注意:此方法在 Windows 本地 NGINX 上不工作
- 脚本将等待任何锁文件被释放,而不是预期的命名锁文件。
- 两个脚本不会同时运行,但一个将等待另一个,而不是退出
依赖关系
This class assumes a LOCK_DIR constant is defined with a value of the directory in which to create the lock file, e.g.:
const LOCK_DIR = '/var/www/mysite.com/locks';
LOCK_DIR should be located outside of any web/code directories so that the code can be updated without affecting any existing lock files.
LOCK_DIR MUST BE WRITABLE BY NGINX.
需求
- PHP 7.1 或更高版本
安装
要安装此模块,请在控制台中运行以下命令
$ composer require "bonsaicode/filelock"
使用方法
<?php
$lock = new BonsaiCode\FileLock( 'MyLock' );
$lockStatus = $lock->acquire();
if( $lockStatus === -1 ) {
echo "Script already running\n";
exit();
} else if( $lockStatus === -2 ) {
echo "Cannot open lock, permission problem?\n";
exit();
}
# Your process code here...
$lock->release();
?>