毫秒定时器主要由三个方法组成
- swoole_timer_tick 设置一个间隔时钟定时器,与after定时器不同的是tick定时器会持续触发,直到调用swoole_timer_clear清除
- swoole_timer_after 在指定的时间后执行函数
- swoole_timer_clear 使用定时器ID来删除定时器
接下来的这个例子是在之前websocket的基础上实现的毫秒定时器。
asyncio_timer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
<?php /** * Created by bingxiong. * Date: 4/17/18 * Time: 3:33 AM * Description: */ class Ws{ CONST HOST="0.0.0.0"; CONST PORT=8812; public $ws = null; public function __construct() { $this->ws = new swoole_websocket_server("0.0.0.0",8812); $this->ws->on("open",[$this,'onOpen']); $this->ws->on("message",[$this,'onMessage']); $this->ws->on("task",[$this,'onTask']); $this->ws->set([ 'worker_num' => 2, 'task_worker_num' => 2, ]); $this->ws->on("finish",[$this,'onFinish']); $this->ws->on("close",[$this,'onClose']); $this->ws->start(); } /** * 监听ws打开事件 * @param $ws * @param $request */ public function onOpen($ws,$request){ var_dump($request->fd); // 如果客户端的id是1,那么每两秒执行 if($request->fd == 1){ swoole_timer_tick(2000,function ($timeId){ echo "The time id is {$timeId}\n"; }); } } /** * 监听ws消息事件 * @param $ws * @param $frame */ public function onMessage($ws,$frame){ echo "server-push-message:{$frame->data}\n"; swoole_timer_after(4000,function () use($ws,$frame){ echo "4s-after\n"; $ws->push($frame->fd,"Server-time-after:"); }); $ws -> push($frame->fd,"server-push:".date("Y-m-d H:i:s")); } /** * @param $serv * @param $taskId * @param $workerId * @param $data */ public function onTask($serv,$taskId,$workerId,$data){ return "on task finish"; // 告诉worker进程 } public function onFinish($serv,$taskId,$data){ echo "taskId:{$taskId}\n"; echo "finish-data-success:{$data}\n"; } /** * 监听关闭事件 * @param $ws * @param $fd */ public function onClose($ws,$fd){ echo "clientId:{$fd}\n"; } } $obj = new Ws(); |
效果:
说明:
- 在这个程序中设置了两个类型的定时器,一种是tick会持续的按照设定的时间间隔执行,另一种是after,会在客户端打开之后一段时间后执行。
- 注意比较控制台的打印顺序,是先打印了之后的逻辑,这是因为这是异步的,执行定时器后不会在这里进行等待而是继续后面的逻辑,因此后面的逻辑被先打印出来
- 程序中用到了闭包函数以及连接闭包和外界变量的关键字use