#文档地址https://wiki.swoole.com/wiki/page/244.html
首先说思路
swoole服务可以常驻内存
所以可以向swoole work进程添加定时器任务
简单实现
demo地址 https://github.com/flyflyhe/swoole-timer
##首先配置swoole http server 注意 work_num 要设置为1 因为如果大于1 定时器就会随机注册到不同的work进程中
$httpServer = new swoole_http_server(LISTEN_IP, LISTEN_PORT); $httpServer->set([ 'task_worker_num' => 10, #如果设置work进程执行过几次就会重启 定时器就消失 #'max_request' => 2, 默认为0 work进程永不reload #woker_num 设置为1 防止定时器找不到进程 'worker_num' => 1, 'user' => 'www', 'group' => 'www' ]);
##设置task进程 所有定时器中执行的任务都应该投递到task进程中 因为work进程只有一个 不能让她阻塞
$httpServer->on('task', function (swoole_server $server, $task_id, $from_id, $data) { echo "$task_id 从 $from_id 获取到数据".$data.PHP_EOL; echo exec("/usr/bin/php /tmp/e.php"); $server->finish($data); }); $httpServer->on('finish', function (swoole_server $server, $task_id, $data) { });
##监听request 请求 设置定时器
$httpServer->on('request', function (swoole_http_request $request, swoole_http_response $response) use ($httpServer, $timeStore, $app) {
$timerId = $server->tick(2000, function()use($httpServer) {
$httpServer->task('hh');
});
$httpServer->task('hh'); $response->write("timer id $timerId"); } }); echo 'listen: '.LISTEN_IP.' port:'.LISTEN_PORT.PHP_EOL; $httpServer->start();