使用swoole 異步毫秒定時器 實現一個簡易restful定時器


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM