php libevent定时器

技术文档 - PHP文档 作者: xcheng1986 发布于:2016-07-29 阅读(625) (暂无评论)  

php利用libevent的定时器做后台定时任务
<?php

/**
 * Timer
 * timer.php
 * @author lixiaocheng<xcheng1986@126.com>
 * @date 2016-7-29
 */
class Timer {

	const TIME_INTVAL = 5000000; //微秒

	public function __construct() {

	}

	/**
	 * run
	 */
	public function run() {

		$base = event_base_new();
		$ev_timer = event_timer_new();
		event_timer_set($ev_timer, array($this, 'timer_fun'), $ev_timer);
		event_base_set($ev_timer, $base);
		event_timer_add($ev_timer, self::TIME_INTVAL);

		event_base_loop($base);
	}

	/**
	 * timer_fun
	 */
	private function timer_fun($event, $flag, $ev_timer) {
		echo date('Y-m-d H:i:s') . "\r\n";
		event_timer_add($ev_timer, self::TIME_INTVAL);
	}

}

$S = new Timer();
$S->run();
运行程序:
/*
[root@192 default]# php timer.php
2016-07-29 20:58:42
2016-07-29 20:58:47
2016-07-29 20:58:52
2016-07-29 20:58:57
2016-07-29 20:59:02
2016-07-29 20:59:07
*/