#文檔地址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();