- 常规定时器
- crontab。但是 crontab 有时候无法满足一些场景,比如需要一些毫秒级、秒级去处理任务的时候。
- Swoole 常规定时器
- swoole_timer_tick:每隔一段时间去执行
- swoole_timer_after:几秒 、几分钟之后去执行
- 参考: https://wiki.swoole.com/wiki/page/p-timer.html
- 实例
# 新开一个终端 1:
cd /data/project/test/swoole/demo/server
vim ws.php
- 修改
ws.php
<?php
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->set([
'worker_num' => 2,
'task_worker_num' => 2
]);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("task", [$this, 'onTask']);
$this->ws->on("finish", [$this, 'onFinish']);
$this->ws->on("close", [$this, 'onClose']);
$this->ws->start();
}
// 监听 ws 连接事件
public function onOpen($ws, $request){
var_dump($request->fd);
if($request->fd == 1){
// 每 2 秒执行
swoole_timer_tick(2000, function($timer_id){
echo "2s: timerId: {$timer_id}\n";
});
}
}
// 监听 ws 消息事件
public function onMessage($ws, $frame){
echo "server-push-message:{$frame->data}\n";
$data = [
'task' => 1,
'fd' => $frame->fd
];
// $ws->task($data);
// 5 秒后执行,异步执行,所以先打印了“server-push:xxx”内容,5 秒后再执行了“server-time-after:xxx”
// 使用 PHP 闭包
swoole_timer_after(5000, function() use($ws, $frame){
echo "5s-after\n";
$ws->push($frame->fd, "server-time-after:5s");
});
$ws->push($frame->fd, "server-push:" . date("Y-m-d H:i:s"));
}
public function onTask($serv, $task_id, $workerId, $data){
print_r($data);
sleep(10);
return 'on task finish';
}
public function onFinish($serv, $taskId, $data){
echo "taskId:{$taskId}\n";
echo "finish-data-success:{$data}\n";
}
// 关闭
public function onClose($ws, $fd){
echo "clientId: {$fd} \n";
}
}
$obj = new Ws();
- 实例操作
# 终端 1 输入如下代码,打开客户端
php ws.php
# 新开一个终端 2,打开 http server
cd /data/project/test/swoole/demo/client
php http_server.php
# 打开浏览器,访问 http://192.168.2.214:8811/ws_client.html