毫秒级,秒级执行任务时,crontab是无法满足任务的。
<?php
/*
* swoole_timer_tick 间隔定时器。
* 持续触发的
* 第一个参数是毫秒,表示 每隔x毫秒执行一次. 1分钟等于60000毫秒,1秒等于1000毫秒
* */
swoole_timer_tick(5000,function ($timer_id){
echo date("Y-m-d H:i:s")."\n";
});
每隔5秒就会冒出一个时间点.
-------------------------------------------------------------------------------------------------------------------
/*
* swoole_timer_after 指定时间后执行函数
* 一次性定时器,执行完成后就会销毁
* 第一个参数是毫秒,表示x毫秒后执行. 1分钟等于60000毫秒,1秒等于1000毫秒 最大不得超过 86400000
* */
swoole_timer_after(5000,function (){
echo date("Y-m-d H:i:s");
});
只执行一次就结束了。
-------------------------------------------------------------------------------------------------------------------
// WebSocket 里测试异步毫秒定时器
class Websocket
{
private $server = null;
public function __construct()
{
$this->server = new swoole_websocket_server("0.0.0.0", 9578);
$this->server->set([
'task_worker_num' => 8, // 启动8个进程来接收异步任务
'worker_num' => 8,
]);
$this->server->on("open", [$this, "onOpen"]);
$this->server->on("message", [$this, "onMessage"]);
$this->server->on("task",[$this,"onTask"]);
$this->server->on("finish", [$this, "onFinish"]);
$this->server->on("close", [$this, "onClose"]);
$this->server->start();
}
public function onOpen($server, $request)
{
$server->push($request->fd, "连接数{$request->fd}");
}
public function onMessage($server, $frame)
{
// 这里用到了背包.
swoole_timer_tick(5000,function() use ($server,$frame){
$server->push($frame->fd,"异步毫秒定时器".date('Y-m-d H:i:s'));
});
$server->push($frame->fd, "服务器返回" . $frame->data . ",时间" . date('Y-m-d H:i:s'));
}
// 处理异步任务
public function onTask($server, $task_id, $src_worker_id, $data)
{
sleep(10); //等待10秒
$server->push($data['fd'], "任务id" . $task_id . ",服务器返回" . $data['content'] . ",时间" . date('Y-m-d H:i:s'));
}
// 将task任务进程的处理结果通过finish返回给worker进程
public function onFinish($server, $task_id, $data)
{
echo "AsyncTask[$task_id] Finish: $data";
}
public function onClose($server, $fd)
{
echo "client {$fd} closed\n";
}
}
$obj = new Websocket();
php a.php
每5秒就会返回一个时间点.