How to set up procss blocking to wait for a signal in PHP

I am writing a timer script using signal. Send a SIGALRM to the process every 1 second, then catch the signal and check if there is a task. I am using pcntl_alarm (1) to send a signal, but the process excute-and-quit before accepting the signal. I am wondering if there is a way to set the lock precess pending signal. I used base_event but its very heavy. So anyone can help me. Thank you so much.

This is my script (Sorry for 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\n";
        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();
    }
}

      

+3


source to share


1 answer


Now I know the answer, although passed away many times because I had other assignments to complete ... sorry lately. So my answer is very simple.

sleep

is good for blocking a process, then the process gets a signal, and what I missed never captures it ... so use



pcntl_signal_dispatch

Function

in the loop matches exactly.

0


source







All Articles