PHP 使用pcntl和libevent 实现Timer功能,先看例子,pcntl(PHP线程)解释在下面。
代码如下:
<?php
function newChild($func_name) {
echo "enter newChild/n";
$args = func_get_args();
unset($args[0]);
$pid = pcntl_fork();
if ($pid == 0) {
function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);
} else if($pid == -1) {
echo "Couldn't create child process";
} else {
return $pid;
}
}
(PS:^_^不错的php开发交流群:256271784,验证:csl,有兴趣的话可以加入进来一起讨论)
function on_timer() {
echo "timer called/n";
}
/**
* @param $func string, function name
* @param $timeouts int, microtimes for time delay
*/
function timer($func, $timeouts){
echo "enter timer/n";
$base = event_base_new();
$event = event_new();
event_set($event, 0, EV_TIMEOUT, $func);
event_base_set($event, $base);
event_add($event, $timeouts);
event_base_loop($base);
}
$pid = newChild("timer", "on_timer", 5000000);
if ($pid > 0) {
echo "master process exit/n";
}
PHP 扩展pcntl 实现 ” 多线程 ”( 进程 )
pcntl 与 ticks
ticks 是通过 declare(ticks = n) {statement} 语法定义的 , declare 语法目前只能接受 ticks, 他定义的 ticks = n 的意义是当 declare 指定的语句块中执行了 N 条低级语句去发生一个事件 , 这个事件可以通过 register_tick_function($function_name) 来注册 .
pcntl 的信号机制是基于 ticks 机制实现的 . 因此 , 我们使用 pcntl 族函数中信号相关的函数时 , 需要在前面增加 declare(ticks = n) 语法结构 .
int pcntl_alarm(int $seconds):
$seconds 秒后向进程发送一个 SIGALRM 信号 , 每次调用 pcntl_alarm 方法都会取消之前设置的时钟 .
void pcntl_exec(string $path[, array $args[, array $env]]):
在当前进程空间执行一个程序 .
$path: 必须是二进制可执行文件 , 或具有有效脚本头信息 (#!/usr/local/bin/php) 的脚本文件路径 .
$args: 将要传递给该程序的字符串参数列表 ( 数组形式 )
$envs: 环境变量 . 以数组 (key => value 形式 ) 方式传递给要执行程序的环境变量 .
新闻热点
疑难解答