I`m writing a Timer script,using a signal.Every 1 second send a SIGALRM to the process,then catch the signal and check whether the there is a task to do. I use pcntl_alarm(1) to send the signal,but the process excute-and-quit,before receive the signal. I think whether there is a method to set the prcess blocked waiting for the signal.I have used base_event,but its much heavy. So anybody can help me.Thanks a lot.
That`s my script(Sorry for the chinesse ^_^):
<?php
/**
*定时器
*/
class Timer
{
//保存所有定时任务
public static $task = array();
//定时间隔
public static $time = 1;
/**
*开启服务
*@param $time int
*/
public static function run($time = null)
{
if($time)
{
self::$time = $time;
}
self::installHandler();
pcntl_alarm(1);
do{ sleep(2); }while(true);
}
/**
*注册信号处理函数
*/
public static function installHandler()
{
echo "installHandler
";
pcntl_signal(SIGALRM, array('Timer','signalHandler'),false);
pcntl_alarm(1);
}
/**
*信号处理函数
*/
public static function signalHandler()
{
self::task();
}
/**
*执行回调
*/
public function task()
{
if(empty(self::$task))
{
return ;
}
foreach(self::$task as $time => $arr)
{
$current = time();
$func = $arr['func'];
$argv = $arr['argv'];
$interval = $arr['interval'];
$persist = $arr['persist'];
if($current == $time)
{
call_user_func_array($func, $argv);
}
if($persist)
{
self::$task[$current+$interval] = $arr;
}
unset(self::$task[$time]);
}
pcntl_alarm(self::$time);
}
/**
*添加任务
public static function add($interval, $func, $argv,$persist = false)
{
if(is_null($interval))
{
return;
}
$time = time()+$interval;
self::$task[$time] = array('func'=>$func, 'argv'=>$argv, 'interval'=>$interval, 'persist'=>$persist);
}
/**
*删除所有定时器任务
*/
public function dellAll()
{
self::$task = array();
}
}