描述
最近在公司部署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 负载.
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | class Timer extends SplMinHeap
{
protected function compare( $value1 , $value2 )
{
if ( $value1 ['timeout'] > $value2 ['timeout']) {
return -1;
}
if ( $value1 ['timeout'] < $value2 ['timeout']) {
return 1;
}
return 0;
}
public function insert( $value )
{
$value ['timeout'] = time() + $value ['expire'];
parent::insert( $value );
}
public function monitor( $debug = false)
{
while (! $this ->isEmpty()) {
$this -> exec ( $debug );
usleep(1000);
}
}
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" : '';
}
}
|
登录后复制
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $timer = new Timer();
$timer ->insert( array ('expire' => 3, 'repeat' => true, 'action' => function (){
echo '3秒 - 重复 - hello world' . "\r\n" ;
}));
$timer ->insert( array ('expire' => 3, 'repeat' => true, 'action' => function (){
echo '3秒 - 重复 - gogo' . "\r\n" ;
}));
$timer ->insert( array ('expire' => 6, 'repeat' => false, 'action' => function (){
echo '6秒 - 一次 - hello xxxx' . "\r\n" ;
}));
$timer ->monitor(false);
|
登录后复制
执行结果

也测试过比较极端的情况,同时1000个定时器1s全部到期,时间堆全部调整完仅需 0.126s 这是没问题的,但是每调整完一个定时器就需要去开启一个子进程,这块可能比较耗时了,有可能1s处理不完这1000个,就会影响下次监听继续触发,但是不开启子进程,比如直接执行应该还是可以处理完的。。。。当然肯定有更好的方法,目前只能想到这样。
以上是PHP多任务秒级定时器的实现方法的详细内容。更多信息请关注PHP中文网其他相关文章!