Swoole异步毫秒定时器

版权声明:转载请注明出处,谢谢。 https://blog.csdn.net/msllws/article/details/84785697

【使用函数】

swoole_timer_tick:设置一个间隔时钟定时器。

swoole_timer_after:在指定的时间后执行函数(1.7.7以上)。

swoole_timer_clear:通过定时器ID删除定时器。

【示例】

以创建一个WebSocket服务设置定时器为例:

ws_server.php:

<?php

class Ws {
    public $ws = null;
    public function __construct() {
        $this->ws = new swoole_websocket_server("0.0.0.0", 9501);
        $this->ws->on("open", [$this, 'onOpen']);
        $this->ws->on("message", [$this, 'onMessage']);
        $this->ws->on("close", [$this, 'onClose']);
        $this->ws->start();
    }

    //建立连接回调
    public function onOpen($ws, $request) {
        echo "标识{$request->fd}建立了连接\n";

        //每2秒执行定时器one
        $timer_one = swoole_timer_tick(2000, function($timer_id) use($request) {
            echo "标识{$request->fd}执行了定时器one,定时器ID:{$timer_id}\n";
        });

        //6秒后执行定时器two 删除定时器one ($timer_one为定时器one的timer_id)
        $timer_two = swoole_timer_after(6000, function () use($timer_one, $request) {
            $res = swoole_timer_clear($timer_one);//删除定时器 返回bool类型
            if($res==true){
                echo "标识{$request->fd}执行了定时器two,清除了定时器ID:{$timer_one}\n";
            }
        });
    }

    //接受消息回调
    public function onMessage($ws, $frame) {
        //服务器返回
        echo "服务器发送消息:{$frame->data}\n";
    }

    //关闭连接回调
    public function onClose($ws, $fd) {
        echo "{$fd}关闭了连接\n";
    }
}

$obj = new Ws();

前端页面js监听:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebSocket</title>
</head>
<body>
</body>
<script type="text/javascript">
var websocket = new WebSocket('ws://127.0.0.1:9501'); 
 
websocket.onopen = function (evt) { onOpen(evt) }; 
websocket.onclose = function (evt) { onClose(evt) }; 
websocket.onmessage = function (evt) { onMessage(evt) }; 
websocket.onerror = function (evt) { onError(evt) }; 
 
function onOpen(evt) {
    console.log("Connected to WebSocket server."); 
    
    //*发送消息到websocket服务器
    websocket.send('666');
} 
function onClose(evt) { 
    console.log("Disconnected"); 
}
function onMessage(evt) { 
    console.log('Retrieved data from server: ' + evt.data); 
} 
function onError(evt) { 
    console.log('Error occured: ' + evt.data); 
}
</script>
</html>

开启WebSocket服务:

php ws_server.php

 刷新页面,WebSocket服务器监听结果:

(服务器会先返回消息给客户端,然后再执行定时器) 

猜你喜欢

转载自blog.csdn.net/msllws/article/details/84785697