1. 程式人生 > 實用技巧 >php如何使用Swoole實現毫秒級定時任務

php如何使用Swoole實現毫秒級定時任務

專案開發中,如果有定時任務的業務要求,我們會使用linux的crontab來解決,但是它的最小粒度是分鐘級別,如果要求粒度是秒級別的,甚至毫秒級別的,crontab就無法滿足,值得慶幸的是swoole提供的強大的毫秒定時器。

應用場景舉例

我們可能會遇到這樣的場景:

  • 場景一:每隔30秒獲取一次本機記憶體使用率

  • 場景二:2分鐘後執行報表傳送任務

  • 場景三:每天凌晨2點鐘定時請求第三方介面,如果介面有資料返回則停止任務,如果介面由於某種原因沒有響應或者沒有資料返回則5分鐘後繼續嘗試請求該介面,嘗試5次後仍然失敗則停止該任務

以上的三個場景我們都可以歸納為定時任務的範疇。

Swoole毫秒定時器

Swoole提供了非同步毫秒定時器函式:

swoole_timer_tick(int $msec, callable $callback):設定一個間隔時鐘定時器,每隔$msec毫秒執行一次$callback,類似於javascript中的setInterval()

swoole_timer_after(int $after_time_ms, mixed $callback_function):在指定的時間$after_time_ms後執行$callback_function,類似於javascript的setTimeout()

swoole_timer_clear(int $timer_id)

:刪除指定id的定時器,類似於javascript的clearInterval()

解決方案

對於場景一,經常用在系統檢測統計方面,實時性要求比較高,但又能控制好頻率,多用於後臺伺服器效能監控,可以生成視覺化圖表。可以是30秒獲取一次記憶體使用率,也可以是10秒,而crontab最小粒度只能設定為1分鐘。

swoole_timer_tick(30000, function($timer) use ($task_id) { // 啟用定時器,每30秒執行一次  
    $memPercent = $this->getMemoryUsage(); //計算記憶體使用率  
    echo date('Y-m-d H:i:s') . '當前記憶體使用率:'.$memPercent."\n";  
});  

對於場景二,直接定義xx時間後執行某項任務的話,貌似crontab比較困難,而使用swoole的swoole_timer_after可以實現:

swoole_timer_after(120000, function() use ($str) { //2分鐘後執行  
    $this->sendReport(); //傳送報表  
    echo "send report, $str\n";  
});  

對於場景三,用來作嘗試請求,請求失敗後繼續,如果成功則停止請求。用crontab也能解決,但是比較傻,比如設定每隔5分鐘請求一次,不管成功會失敗都會去執行一次。而用swoole定時器則智慧多了。

swoole_timer_tick(5*60*1000, function($timer) use ($url) { // 啟用定時器,每5分鐘執行一次  
      $rs = $this->postUrl($url);  

      if ($rs) {  
          //業務程式碼...  
          swoole_timer_clear($timer); // 停止定時器  
          echo date('Y-m-d H:i:s'). "請求介面任務執行成功\n";  
      } else {  
          echo date('Y-m-d H:i:s'). "請求介面失敗,5分鐘後再次嘗試\n";  
     }  
 });  

示例程式碼

新建檔案\src\App\Task.php:

namespace Helloweba\Swoole;  

use swoole_server;  

/**  
* 任務排程  
*/  
class Task  
{  
    protected $serv;  
    protected $host = '127.0.0.1';  
    protected $port = 9506;  
    // 程序名稱  
    protected $taskName = 'swooleTask';  
    // PID路徑  
    protected $pidPath = '/run/swooletask.pid';  
    // 設定執行時引數  
    protected $options = [  
        'worker_num' => 4, //worker程序數,一般設定為CPU數的1-4倍   
        'daemonize' => true, //啟用守護程序  
        'log_file' => '/data/log/swoole-task.log', //指定swoole錯誤日誌檔案  
        'log_level' => 0, //日誌級別 範圍是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR  
        'dispatch_mode' => 1, //資料包分發策略,1-輪詢模式  
        'task_worker_num' => 4, //task程序的數量  
        'task_ipc_mode' => 3, //使用訊息佇列通訊,並設定為爭搶模式  
    ];  

    public function __construct($options = [])  
    {  
        date_default_timezone_set('PRC');  
        // 構建Server物件,監聽127.0.0.1:9506埠  
        $this->serv = new swoole_server($this->host, $this->port);  

        if (!empty($options)) {  
            $this->options = array_merge($this->options, $options);  
        }  
        $this->serv->set($this->options);  

        // 註冊事件  
        $this->serv->on('Start', [$this, 'onStart']);  
        $this->serv->on('Connect', [$this, 'onConnect']);  
        $this->serv->on('Receive', [$this, 'onReceive']);  
        $this->serv->on('Task', [$this, 'onTask']);   
        $this->serv->on('Finish', [$this, 'onFinish']);  
        $this->serv->on('Close', [$this, 'onClose']);  
    }  

    public function start()  
    {  
        // Run worker  
        $this->serv->start();  
    }  

    public function onStart($serv)  

    {  
        // 設定程序名  
        cli_set_process_title($this->taskName);  
        //記錄程序id,指令碼實現自動重啟  
        $pid = "{$serv->master_pid}\\n{$serv->manager_pid}";  
        file_put_contents($this->pidPath, $pid);  
    }  

    //監聽連線進入事件  
    public function onConnect($serv, $fd, $from_id)  
    {  
        $serv->send( $fd, "Hello {$fd}!" );  
    }  

    // 監聽資料接收事件  
    public function onReceive(swoole_server $serv, $fd, $from_id, $data)  
    {  
        echo "Get Message From Client {$fd}:{$data}\n";  
        //$this->writeLog('接收客戶端引數:'.$fd .'-'.$data);  
        $res['result'] = 'success';  
        $serv->send($fd, json_encode($res)); // 同步返回訊息給客戶端  
        $serv->task($data);  // 執行非同步任務  
    }  

    /**  
  
    * @param $serv swoole_server swoole_server物件  
    * @param $task_id int 任務id  
    * @param $from\id int 投遞任務的worker_id  
    * @param $data string 投遞的資料  
    */  
    public function onTask(swoole_server $serv, $task_id, $from_id, $data)  
    {  
        swoole_timer_tick(30000, function($timer) use ($task_id) { // 啟用定時器,每30秒執行一次  
            $memPercent = $this->getMemoryUsage();  
            echo date('Y-m-d H:i:s') . '當前記憶體使用率:'.$memPercent."\n";  
        });  
    }  


    /**  
    * @param $serv swoole_server swoole_server物件  
    * @param $task_id int 任務id  
    * @param $data string 任務返回的資料  
    */  
    public function onFinish(swoole_server $serv, $task_id, $data)  
    {  
        //  
    }  

  
    // 監聽連線關閉事件  
    public function onClose($serv, $fd, $from_id) {  
        echo "Client {$fd} close connection\n";  
    }  

    public function stop()  
    {  
        $this->serv->stop();  
    }  

    private function getMemoryUsage()  
    {  
        // MEMORY  
        if (false === ($str = @file("/proc/meminfo"))) return false;  
        $str = implode("", $str);  
        preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buf);  
        //preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buffers);  

        $memTotal = round($buf[1][0]/1024, 2);  
        $memFree = round($buf[2][0]/1024, 2);  
        $memUsed = $memTotal - $memFree;  
        $memPercent = (floatval($memTotal)!=0) ? round($memUsed/$memTotal*100,2):0;  

        return $memPercent;  
    }  
}  

我們以場景一為例,在onTask啟用定時任務,每隔30秒計算一次記憶體使用率。實際應用中可以把計算好的記憶體按時間寫入資料庫等儲存中,然後可以根據前端需求用來渲染成統計圖表,如:

接著服務端程式碼 public\taskServer.php :

<?php
require dirname(__DIR__) . '/vendor/autoload.php';  
use Helloweba\Swoole\Task;  
$opt = [  
    'daemonize' => false  
];  
$ser = new Task($opt);  
$ser->start();  

客戶端程式碼 public\taskClient.php :

<?php
class Client  
{  
    private $client;  
    public function __construct() {  
        $this->client = new swoole_client(SWOOLE_SOCK_TCP);  
    }  
    public function connect() {  
        if( !$this->client->connect("127.0.0.1", 9506 , 1) ) {  
            echo "Error: {$this->client->errMsg}[{$this->client->errCode}]\n";  
          }  
        fwrite(STDOUT, "請輸入訊息 Please input msg:");  
        $msg = trim(fgets(STDIN));  
        $this->client->send( $msg );  
        $message = $this->client->recv();  
        echo "Get Message From Server:{$message}\n";  
    }  
}  
$client = new Client();  
$client->connect();  

驗證效果

1.啟動服務端:

php taskServer.php

2.客戶端輸入:

另開命令列視窗,執行

[root@localhost public]# php taskClient.php  

請輸入訊息 Please input msg:hello

Get Message From Server:{"result":"success"}  
[root@localhost public]#  

3.服務端返回:

如果返回上圖中的結果,則定時任務正常執行,我們會發現每隔30秒會輸出一條資訊。


更多學習內容可以訪問【對標大廠】精品PHP架構師教程目錄大全,只要你能看完保證薪資上升一個臺階(持續更新)

以上內容希望幫助到大家,很多PHPer在進階的時候總會遇到一些問題和瓶頸,業務程式碼寫多了沒有方向感,不知道該從那裡入手去提升,對此我整理了一些資料,包括但不限於:分散式架構、高可擴充套件、高效能、高併發、伺服器效能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell指令碼、Docker、微服務、Nginx等多個知識點高階進階乾貨需要的可以免費分享給大家,需要的可以加入我的PHP技術交流群953224940

進階PHP月薪30k>>>架構師成長路線【視訊、面試文件免費獲取】