swoole 清除定時器提示no timer
阿新 • • 發佈:2018-11-16
首頁確定一個核心概念
clearTimer
僅可清除當前程序的定時器
server程式碼如下:
<?php class Server { private $serv; private $timer; public function __construct() { $this->serv = new swoole_server("0.0.0.0", 9501); $this->serv->set([ 'worker_num' => 8, 'daemonize' => false, ]); $this->serv->on('Start', [$this, 'onStart']); $this->serv->on('Connect', [$this, 'onConnect']); $this->serv->on('Receive', [$this, 'onReceive']); $this->serv->on('Close', [$this, 'onClose']); $this->serv->start(); } public function onStart($serv) { $this->echoStr("Server Starting"); $this->timer = $serv->tick(1000, function(){ $this->echoStr("timer waiting"); }); // $this->timer = swoole_timer_tick(1000, function() { // }); } public function onConnect($serv, $fd, $from_id) { // swoole_timer_clear($this->timer); $serv->clearTimer($this->timer); $this->echoStr("Connecting! Clear Timer!"); // $serv->send($fd, "Hello {$fd}!"); } public function onReceive(swoole_server $serv, $fd, $from_id, $data) { $this->echoStr("Get Message From Client {$fd}:{$data}"); $serv->send($fd, $data); } public function onClose($serv, $fd, $from_id) { $this->echoStr("Client {$fd} close connection"); } public function echoStr($msg) { echo '[' . date('Y-m-d H:i:s') . ']: ' . $msg . PHP_EOL; } } // 啟動伺服器 Start the server $server = new Server();
本意圖實現server啟動後迴圈輸出“timer waiting”,client連線後清除定時器的效果,然而onStart事件是在Master程序的主執行緒中被呼叫,而onConnect事件是在work程序中被回撥,這裡不屬於同一程序,故client連線後會提示:
PHP Warning: SwooleServer::clearTimer(): no timer...