当前位置:网站首页>PHP 多任务秒级定时器的实现方法
PHP 多任务秒级定时器的实现方法
2022-07-26 05:57:00 【lxw1844912514】
1.描述
最近在公司部署crontab的时候,突发奇想是否可以用PHP去实现一个定时器,颗粒度到秒级就好,因为crontab最多到分钟级别,同时也调研了一下用PHP去实现的定时器还真不太多,Swoole 扩展里面到实现了一个毫秒级的定时器很高效,但毕竟不是纯PHP代码写的,所以最后还是考虑用PHP去实现一个定时器类,以供学习参考。
2.代码实现
在实现定时器代码的时候,用到了PHP系统自带的两个扩展
Pcntl - 多进程扩展 :
主要就是让PHP可以同时开启很多子进程,并行的去处理一些任务。
Spl - SplMinHeap - 小顶堆
一个小顶堆数据结构,在实现定时器的时候,采用这种结构效率还是不错的,插入、删除的时间复杂度都是 O(logN) ,像 libevent 的定时器也在 1.4 版本以后采用了这种数据结构之前用的是 rbtree,如果要是使用链表或者固定的数组,每次插入、删除可能都需要重新遍历或者排序,还是有一定的性能问题的。
3.流程

说明
1、定义定时器结构,有什么参数之类的.
2、然后全部注册进我们的定时器类 Timer.
3、调用定时器类的monitor方法,开始进行监听.
4、监听过程就是一个while死循环,不断的去看时间堆的堆顶是否到期了,本来考虑每秒循环看一次,后来一想每秒循环看一次还是有点问题,如果正好在我们sleep(1)的时候定时器有到期的了,那我们就不能马上去精准执行,可能会有延时的风险,所以还是采用 usleep(1000) 毫秒级的去看并且也可以将进程挂起减轻 CPU 负载.
4.代码
<?php
/**** 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" : '';
}
}5.实例
<?php
$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)6.执行结果

相关文章

边栏推荐
- Redis persistence RDB
- Detailed explanation of the whole process of coding's pressure measurement operation
- No EGL display error resolution
- [(SV & UVM) knowledge points encountered in written interview] ~ phase mechanism
- leetcode-aboutString
- 语法泛化三种可行方案介绍
- 柠檬班自动化学习毕竟
- 中文文本纠错任务简介
- ament_cmake生成ROS2库并链接
- Establishment of log collection and analysis platform-1-environment preparation
猜你喜欢
![[paper notes] anti packet loss joint coding for network speech steganography](/img/ca/95476b6d4b5765f5fde82cbeda577e.png)
[paper notes] anti packet loss joint coding for network speech steganography

The refurbishment and counterfeiting of chips have made people feel numb

递归处理——子问题

Redis事务
![ERROR: Could not open requirements file: [Errno 2] No such file or directory: ‘requirments.txt’](/img/15/25ff1e544565e18319ecca85e614a2.png)
ERROR: Could not open requirements file: [Errno 2] No such file or directory: ‘requirments.txt’

逆序打印链表

漫谈软件缺陷管理的实践

The idea YML file code does not prompt the solution

Efficient, reliable and safe open source solution for serial communication

Using easyexcel to import tables to realize batch insertion of xlsx files ----- MySQL of Linux
随机推荐
Embedded general learning route arrangement
Redis persistence RDB
Should we test the Dao layer?
【Oracle SQL】计算同比与环比(列转行进行偏移)
[MySQL must know and know] time function number function string function condition judgment
L. Link with Level Editor I dp
Motor control column summary
Byte interview question - judge whether a tree is a balanced binary tree
[2023 Jerry technology approval test questions in advance] ~ questions and reference answers
【2023杰理科技提前批笔试题】~ 题目及参考答案
平衡二叉树(AVL) ~
[highly available MySQL solution] centos7 configures MySQL master-slave replication
程序员如何改善精神内耗?
Benji Bananas 开启第二季边玩边赚奖励活动,支持使用多张 Benji 通行证!
Unity Profiler
光量子里程碑:6分钟内解决3854个变量问题
vagrant下载速度慢的解决方法
Ros2 preliminary: basic communication with topic
Redis主从复制
[cloud native] record of feign custom configuration of microservices