epsiloncool / db-semaphore
纯PHP实现的简洁高效的信号量实现
dev-master
2019-05-18 19:38 UTC
Requires
- php: >=5.3.0
- ext-mysqli: *
This package is auto-updated.
Last update: 2024-09-19 07:54:36 UTC
README
纯PHP实现的简洁高效的信号量实现
如果你想要管理一段PHP代码,这段代码只能运行一次,可以使用这个库。
它可以用在很多地方,比如cronjob脚本。当cronjob定期被操作系统运行时,如果脚本在上一次运行中仍然在执行,我们不应该再次运行脚本。信号量可以帮助我们处理这种情况。
安装
使用以下命令安装最新版本:
$ composer require epsiloncool/db-semaphore
从文件 sql/dbsem_locks.sql
导入sql数据
基本用法
<?php
use Epsiloncool\Utils;
$db = GetDBLink(); // Get MySQLi instance from your app environment
$process_id = md5(uniqid('random_process_id')); // Create random process ID
global $sem;
// Create a new semaphore for this task "task_identifier"
$sem = new DB_Semaphore($db, 'dbsem', $process_id, 'task_identifier');
$sem->timeout = 600; // Set a time, when the semaphore will be busy with this process even on process fail
// Trying to reserve a semaphore for this process
if (!$sem->Enter()) {
echo 'Another instance of this process is running. Stopped.'."\n";
exit();
}
// Ok, we allowed to execute
// ... Do some actions
$sem->Update(); // We have to call this method periodically with the guaranteed interval of half of "timeout" value
// ...More actions
$sem->Update(); // Remember to call this periodically
// Release the semaphore on the end of the task (allow to rerun this task)
$sem->Leave();
echo 'This task is completed';
变更日志
v1.0.2
- 详细文档
v1.0.1
- 添加了Check()方法
v1.0.0
- 初始发布