问题代码
class Events
{
public static function onWorkerStart()
{
Timer::add(1, function(){
//echo "timer:".time()."\n";
list($msec, $sec) = explode(' ', microtime());
$msectime = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
$time=array();
$time['time']=$msectime;
$message = array();
$message["code"]=201;//定时器
$message["message"]='time '.$msectime;
$message["data"]=$time;
Gateway::sendToAll(json_encode($message));
});
}
这个定时器代码每秒群发消息给客户端进行倒计时,当多进程的时候每个进程都会启动一个定时器来群发消息,在客户端访问不频繁的情况下,不会出现阻塞的情况,当客户端和服务器间频繁发送消息的时候,客户端一次接受所有进程的消息,导致处理不过来卡顿的问题会很严重,其实只需要一个进程启动定时器,群发消息即可于是对进程id进行了判断,修改过的代码如下:
class Events
{
public static function onWorkerStart($worker)
{
//Gateway::sendToAll('workerid'.$businessWorker->id);
if($worker->id === 0){
Timer::add(1, function(){
//echo "timer:".time()."\n";
list($msec, $sec) = explode(' ', microtime());
$msectime = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
$time=array();
$time['time']=$msectime;
$message = array();
$message["code"]=201;//定时器
$message["message"]='time '.$msectime;
$message["data"]=$time;
Gateway::sendToAll(json_encode($message));
});
}
}
参考文章:https://www.workerman.net/q/4568
Mikel