首頁肯定一個核心概念php
clearTimer
僅可清除當前進程的定時器
server代碼以下:html
<?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...