PHP 多任务秒级定时器的实现方法
描述
近期在公司部署 crontab 时产生了一个想法:能否用 PHP 实现颗粒度达到秒级的定时器?因为 crontab 最高精度仅为分钟级。经过调研发现,基于 PHP 实现的定时器案例较少。虽然 Swoole 扩展提供了高效的毫秒级定时器,但其并非纯 PHP 代码编写。因此,最终决定尝试使用纯 PHP 代码实现一个定时器类,供学习参考。
实现
在编写定时器代码的过程中,主要依赖了 PHP 系统自带的两个扩展模块。
Pcntl - 多进程扩展 :
该扩展的主要作用是允许 PHP 同时启动多个子进程,从而并行地执行各类任务,提升处理效率。
Spl - SplMinHeap - 小顶堆
小顶堆是一种数据结构,在定时器实现中采用此结构能获得不错的效率。其插入和删除操作的时间复杂度均为 O(logN)。例如 libevent 的定时器在 1.4 版本后便采用了这种结构(此前使用 rbtree)。若使用链表或固定数组,每次插入或删除都可能需要重新遍历或排序,存在性能瓶颈。
流程

说明
1、定义定时器结构,包含参数等配置。 2、将所有任务注册进定时器类 Timer。 3、调用定时器类的 monitor 方法,开始监听。 4、监听过程是一个 while 死循环,不断检查时间堆的堆顶是否已到期。原本考虑每秒循环一次,但发现若在 sleep(1) 期间有任务到期,无法立即精准执行,存在延时风险。因此改为采用 usleep(1000) 进行毫秒级检查,既能保证精度,又能挂起进程以降低 CPU 负载。
代码
/***
* Class Timer
*/
class Timer extends SplMinHeap
{
/**
* 比较根节点和新插入节点大小
* @param mixed $value1
* @param mixed $value2
* @return int
*/
protected function compare($value1, $value2)
{
if ($value1['timeout'] > $value2['timeout']) {
return -1;
}
if ($value1['timeout'] < $value2['timeout']) {
return 1;
}
return 0;
}
/**
* 插入节点
* @param mixed $value
*/
public function insert($value)
{
$value['timeout'] = time() + $value['expire'];
parent::insert($value);
}
/**
* 监听
* @param bool $debug
*/
public function monitor($debug = false)
{
while (!$this->isEmpty()) {
$this->exec($debug);
usleep(1000);
}
}
/**
* 执行
* @param $debug
*/
private function exec($debug)
{
$hit = 0;
$t1 = microtime(true);
while (!$this->isEmpty()) {
$node = $this->top();
if ($node['timeout'] <= time()) {
//出堆或入堆
$node['repeat'] ? $this->insert($this->extract()) : $this->extract();
$hit = 1;
//开启子进程
if (pcntl_fork() == 0) {
empty($node['action']) ? '' : call_user_func($node['action']);
exit(0);
}
//忽略子进程,子进程退出由系统回收
pcntl_signal(SIGCLD, SIG_IGN);
} else {
break;
}
}
$t2 = microtime(true);
echo ($debug && $hit) ? '时间堆 - 调整耗时: ' . round($t2 - $t1, 3) . "秒\r\n" : '';
}
}
实例
$timer = new Timer();
//注册 - 3s - 重复触发
$timer->insert(array('expire' => 3, 'repeat' => true, 'action' => function(){
echo '3秒 - 重复 - hello world' . "\r\n";
}));
//注册 - 3s - 重复触发
$timer->insert(array('expire' => 3, 'repeat' => true, 'action' => function(){
echo '3秒 - 重复 - gogo' . "\r\n";
}));
//注册 - 6s - 触发一次
$timer->insert(array('expire' => 6, 'repeat' => false, 'action' => function(){
echo '6秒 - 一次 - hello xxxx' . "\r\n";
}));
//监听
$timer->monitor(false);
执行结果

测试过极端情况:同时创建 1000 个 1 秒到期的定时器,时间堆全部调整完毕仅需 0.126 秒,这部分没有问题。但是,每调整完一个定时器就需要开启一个子进程,这块比较耗时,可能导致 1 秒内处理不完这 1000 个任务,从而影响下一次的监听触发。如果不开启子进程,直接执行应该可以处理完。当然肯定有更好的方法,目前只能想到这样。
总结
以上所述是小编给大家介绍的PHP 多任务秒级定时器的实现方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!