123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- /**
- * 定时器管理类
- */
- class TimerMan
- {
- /**
- * 定时器列表
- * @var array
- */
- protected $timers;
- /**
- * ID值
- * @int
- */
- protected $id;
- /**
- * 定时器到期时间
- */
- protected $nextTimeout;
- /**
- * 构造函数
- */
- public function __construct()
- {
- $this->timers = [];
- $this->nextTimeout = 0;
- }
- /**
- * 添加定时器
- * @param int $ms 毫秒数
- * @param mixed $handle 回调函数
- * @param mixed $args 回调函数参数
- * @return int 定时器ID
- */
- public function add($ms, $handle, $args = [])
- {
- $now = floor(microtime(true) * 1000);
- $to = $now + $ms;
- if (!$this->nextTimeout || $to < $this->nextTimeout) {
- $this->nextTimeout = $to;
- }
- $this->timers[++$this->id] = [
- $to,
- $handle,
- is_array($args) ? $args : [$args],
- ];
- return $this->id;
- }
- /**
- * 清除定时器
- * @param int $id 定时器ID
- */
- public function clear($id)
- {
- if (isset($this->timers[$id])) {
- unset($this->timers[$id]);
- }
- }
- /**
- * 取select应当等待的时长
- */
- public function getWaitTime()
- {
- if (!$this->nextTimeout) {
- return [NULL, NULL];
- }
- $now = floor(microtime(true) * 1000);
- if ($now >= $this->nextTimeout) {
- return [NULL, NULL];
- }
- $ms = $this->nextTimeout - $now;
- if ($ms < 10) {
- return [0, 10];
- }
- return [floor($ms/1000), $ms%1000];
- }
- /**
- * 定时器的循环检测代码
- */
- public function interval()
- {
- $cnt = 0;
- $now = floor(microtime(true) * 1000) + 10; //误差10
- $timeouted = [];
- $min = 0;
- foreach ($this->timers as $id => $item) {
- if ($item[0] <= $now) {
- $timeouted[$id] = $item;
- unset($this->timers[$id]);
- }
- $min = $min == 0 ? $item[0] : min($min, $item[0]);
- }
- foreach ($timeouted as $id => $item) {
- call_user_func_array($item[1], $item[2]);
- }
- $this->nextTimeout = $min;
- }
- }
|