php Swoole實(shí)現(xiàn)毫秒級(jí)定時(shí)任務(wù)

php Swoole實(shí)現(xiàn)毫秒級(jí)定時(shí)任務(wù)

項(xiàng)目開發(fā)中,如果有定時(shí)任務(wù)的業(yè)務(wù)要求,我們會(huì)使用linux的crontab來解決,但是它的最小粒度是分鐘級(jí)別,如果要求粒度是秒級(jí)別的,甚至毫秒級(jí)別的,crontab就無法滿足,值得慶幸的是swoole提供的強(qiáng)大的毫秒定時(shí)器。

推薦學(xué)習(xí):?swoole教程

應(yīng)用場景舉例

我們可能會(huì)遇到這樣的場景:

●?場景一:每隔30秒獲取一次本機(jī)內(nèi)存使用率

立即學(xué)習(xí)PHP免費(fèi)學(xué)習(xí)筆記(深入)”;

●?場景二:2分鐘后執(zhí)行報(bào)表發(fā)送任務(wù)

●?場景三:每天凌晨2點(diǎn)鐘定時(shí)請求第三方接口,如果接口有數(shù)據(jù)返回則停止任務(wù),如果接口由于某種原因沒有響應(yīng)或者沒有數(shù)據(jù)返回則5分鐘后繼續(xù)嘗試請求該接口,嘗試5次后仍然失敗則停止該任務(wù)

以上的三個(gè)場景我們都可以歸納為定時(shí)任務(wù)的范疇。

swoole毫秒定時(shí)器

Swoole提供了異步毫秒定時(shí)器函數(shù):

swoole_timer_tick(int $msec, callable $callback):設(shè)置一個(gè)間隔時(shí)鐘定時(shí)器,每隔$msec毫秒執(zhí)行一次$callback,類似于JavaScript中的setInterval()。

swoole_timer_after(int $after_time_ms, mixed $callback_function):在指定的時(shí)間$after_time_ms后執(zhí)行$callback_function,類似于javascript的setTimeout()。

swoole_timer_clear(int $timer_id):刪除指定id的定時(shí)器,類似于javascript的clearInterval()。

解決方案

對(duì)于場景一,經(jīng)常用在系統(tǒng)檢測統(tǒng)計(jì)方面,實(shí)時(shí)性要求比較高,但又能控制好頻率,多用于后臺(tái)服務(wù)器性能監(jiān)控,可以生成可視化圖表。可以是30秒獲取一次內(nèi)存使用率,也可以是10秒,而crontab最小粒度只能設(shè)置為1分鐘。

?swoole_timer_tick(30000,?function($timer)?use?($task_id)?{?//?啟用定時(shí)器,每30秒執(zhí)行一次 ?????$memPercent?=?$this->getMemoryUsage();?//計(jì)算內(nèi)存使用率 ?????echo?date('Y-m-d?H:i:s')?.?'當(dāng)前內(nèi)存使用率:'.$memPercent."n"; ?});

?

?

對(duì)于場景二,直接定義xx時(shí)間后執(zhí)行某項(xiàng)任務(wù)的話,貌似crontab比較困難,而使用swoole的swoole_timer_after可以實(shí)現(xiàn):

?swoole_timer_after(120000,?function()?use?($str)?{?//2分鐘后執(zhí)行 ?????$this->sendReport();?//發(fā)送報(bào)表 ?????echo?"send?report,?$strn"; ?});

?

對(duì)于場景三,用來作嘗試請求,請求失敗后繼續(xù),如果成功則停止請求。用crontab也能解決,但是比較傻,比如設(shè)置每隔5分鐘請求一次,不管成功會(huì)失敗都會(huì)去執(zhí)行一次。而用swoole定時(shí)器則智能多了。

swoole_timer_tick(5*60*1000,?function($timer)?use?($url)?{?//?啟用定時(shí)器,每5分鐘執(zhí)行一次 ??????$rs?=?$this->postUrl($url); ?? ??????if?($rs)?{ ??????????//業(yè)務(wù)代碼... ??????????swoole_timer_clear($timer);?//?停止定時(shí)器 ??????????echo?date('Y-m-d?H:i:s').?"請求接口任務(wù)執(zhí)行成功n"; ??????}?else?{ ??????????echo?date('Y-m-d?H:i:s').?"請求接口失敗,5分鐘后再次嘗試n"; ?????} ?});

?

示例代碼

新建文件srcAppTask.php

<?php   namespace HellowebaSwoole;  use swoole_server;  /** * 任務(wù)調(diào)度 */ class Task {     protected $serv;     protected $host = &#39;127.0.0.1&#39;;     protected $port = 9506;     // 進(jìn)程名稱     protected $taskName = &#39;swooleTask&#39;;     // PID路徑     protected $pidPath = &#39;/run/swooletask.pid&#39;;     // 設(shè)置運(yùn)行時(shí)參數(shù)     protected $options = [         &#39;worker_num&#39; =>?4,?//worker進(jìn)程數(shù),一般設(shè)置為CPU數(shù)的1-4倍?? ????????'daemonize'?=&gt;?true,?//啟用守護(hù)進(jìn)程 ????????'log_file'?=&gt;?'/data/log/swoole-task.log',?//指定swoole錯(cuò)誤日志文件 ????????'log_level'?=&gt;?0,?//日志級(jí)別?范圍是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR ????????'dispatch_mode'?=&gt;?1,?//數(shù)據(jù)包分發(fā)策略,1-輪詢模式 ????????'task_worker_num'?=&gt;?4,?//task進(jìn)程的數(shù)量 ????????'task_ipc_mode'?=&gt;?3,?//使用消息隊(duì)列通信,并設(shè)置為爭搶模式 ????];  ????public?function?__construct($options?=?[]) ????{ ????????date_default_timezone_set('PRC');? ????????//?構(gòu)建Server對(duì)象,監(jiān)聽127.0.0.1:9506端口 ????????$this-&gt;serv?=?new?swoole_server($this-&gt;host,?$this-&gt;port);  ????????if?(!empty($options))?{ ????????????$this-&gt;options?=?array_merge($this-&gt;options,?$options); ????????} ????????$this-&gt;serv-&gt;set($this-&gt;options);  ????????//?注冊事件 ????????$this-&gt;serv-&gt;on('Start',?[$this,?'onStart']); ????????$this-&gt;serv-&gt;on('Connect',?[$this,?'onConnect']); ????????$this-&gt;serv-&gt;on('Receive',?[$this,?'onReceive']); ????????$this-&gt;serv-&gt;on('Task',?[$this,?'onTask']);?? ????????$this-&gt;serv-&gt;on('Finish',?[$this,?'onFinish']); ????????$this-&gt;serv-&gt;on('Close',?[$this,?'onClose']); ????}  ????public?function?start() ????{ ????????//?Run?worker ????????$this-&gt;serv-&gt;start(); ????}  ????public?function?onStart($serv) ????{ ????????//?設(shè)置進(jìn)程名 ????????cli_set_process_title($this-&gt;taskName); ????????//記錄進(jìn)程id,腳本實(shí)現(xiàn)自動(dòng)重啟 ????????$pid?=?"{$serv-&gt;master_pid}n{$serv-&gt;manager_pid}"; ????????file_put_contents($this-&gt;pidPath,?$pid); ????}  ????//監(jiān)聽連接進(jìn)入事件 ????public?function?onConnect($serv,?$fd,?$from_id) ????{ ????????$serv-&gt;send(?$fd,?"Hello?{$fd}!"?); ????}  ????//?監(jiān)聽數(shù)據(jù)接收事件 ????public?function?onReceive(swoole_server?$serv,?$fd,?$from_id,?$data) ????{ ????????echo?"Get?Message?From?Client?{$fd}:{$data}n"; ????????//$this-&gt;writeLog('接收客戶端參數(shù):'.$fd?.'-'.$data); ????????$res['result']?=?'success'; ????????$serv-&gt;send($fd,?json_encode($res));?//?同步返回消息給客戶端 ????????$serv-&gt;task($data);??//?執(zhí)行異步任務(wù) ????}  ????/** ????*?@param?$serv?swoole_server?swoole_server對(duì)象 ????*?@param?$task_id?int?任務(wù)id ????*?@param?$from_id?int?投遞任務(wù)的worker_id ????*?@param?$data?string?投遞的數(shù)據(jù) ????*/ ????public?function?onTask(swoole_server?$serv,?$task_id,?$from_id,?$data) ????{ ????????swoole_timer_tick(30000,?function($timer)?use?($task_id)?{?//?啟用定時(shí)器,每30秒執(zhí)行一次 ????????????$memPercent?=?$this-&gt;getMemoryUsage(); ????????????echo?date('Y-m-d?H:i:s')?.?'當(dāng)前內(nèi)存使用率:'.$memPercent."n"; ????????}); ????}   ????/** ????*?@param?$serv?swoole_server?swoole_server對(duì)象 ????*?@param?$task_id?int?任務(wù)id ????*?@param?$data?string?任務(wù)返回的數(shù)據(jù) ????*/ ????public?function?onFinish(swoole_server?$serv,?$task_id,?$data) ????{ ????????// ????}   ????//?監(jiān)聽連接關(guān)閉事件 ????public?function?onClose($serv,?$fd,?$from_id)?{ ????????echo?"Client?{$fd}?close?connectionn"; ????}  ????public?function?stop() ????{ ????????$this-&gt;serv-&gt;stop(); ????}  ????private?function?getMemoryUsage() ????{ ????????//?MEMORY ????????if?(false?===?($str?=?@file("/proc/meminfo")))?return?false; ????????$str?=?implode("",?$str); ????????preg_match_all("/MemTotals{0,}:+s{0,}([d.]+).+?MemFrees{0,}:+s{0,}([d.]+).+?Cacheds{0,}:+s{0,}([d.]+).+?SwapTotals{0,}:+s{0,}([d.]+).+?SwapFrees{0,}:+s{0,}([d.]+)/s",?$str,?$buf); ????????//preg_match_all("/Bufferss{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啟用定時(shí)任務(wù),每隔30秒計(jì)算一次內(nèi)存使用率。實(shí)際應(yīng)用中可以把計(jì)算好的內(nèi)存按時(shí)間寫入數(shù)據(jù)庫等存儲(chǔ)中,然后可以根據(jù)前端需求用來渲染成統(tǒng)計(jì)圖表,如:

php Swoole實(shí)現(xiàn)毫秒級(jí)定時(shí)任務(wù)

接著服務(wù)端代碼 publictaskServer.php :

<?php   require dirname(__DIR__) . &#39;/vendor/autoload.php&#39;; use HellowebaSwooleTask; $opt = [     &#39;daemonize&#39; =>?false ]; $ser?=?new?Task($opt); $ser-&gt;start();

?

?

客戶端代碼 publictaskClient.php :

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

?

驗(yàn)證效果

1.啟動(dòng)服務(wù)端:

php taskServer.php

?

2.客戶端輸入:

另開命令行窗口,執(zhí)行

[root@localhost?public]#?php?taskClient.php

請輸入消息 Please input msg:hello

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

?

3.服務(wù)端返回:

php Swoole實(shí)現(xiàn)毫秒級(jí)定時(shí)任務(wù)

如果返回上圖中的結(jié)果,則定時(shí)任務(wù)正常運(yùn)行,我們會(huì)發(fā)現(xiàn)每隔30秒會(huì)輸出一條信息。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊5 分享