php swoole 任务调度,php Swoole实现毫秒级定时任务

项目开发中,若是有定时任务的业务要求,咱们会使用linux的crontab来解决,可是它的最小粒度是分钟级别,若是要求粒度是秒级别的,甚至毫秒级别的,crontab就没法知足,值得庆幸的是swoole提供的强大的毫秒定时器。

应用场景举例

咱们可能会遇到这样的场景:javascript

场景一:每隔30秒获取一次本机内存使用率

场景二:2分钟后执行报表发送任务

场景三:天天凌晨2点钟定时请求第三方接口,若是接口有数据返回则中止任务,若是接口因为某种缘由没有响应或者没有数据返回则5分钟后继续尝试请求该接口,尝试5次后仍然失败则中止该任务

以上的三个场景咱们均可以概括为定时任务的范畴。

Swoole毫秒定时器

Swoole提供了异步毫秒定时器函数:php

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()。java

swoole_timer_clear(int $timer_id):删除指定id的定时器,相似于javascript的clearInterval()。linux

解决方案

对于场景一,常常用在系统检测统计方面,实时性要求比较高,但又能控制好频率,多用于后台服务器性能监控,能够生成可视化图表。能够是30秒获取一次内存使用率,也能够是10秒,而crontab最小粒度只能设置为1分钟。web

1 swoole_timer_tick(30000, function($timer) use ($task_id) { //启用定时器,每30秒执行一次

2 $memPercent = $this->getMemoryUsage(); //计算内存使用率

3 echo date('Y-m-d H:i:s') . '当前内存使用率:'.$memPercent."\n";4 });

bf503107f38c4b8c92006c7c.html

对于场景二,直接定义xx时间后执行某项任务的话,貌似crontab比较困难,而使用swoole的swoole_timer_after能够实现:数据库

1 swoole_timer_after(120000, function() use ($str) { //2分钟后执行

2 $this->sendReport(); //发送报表

3 echo "send report, $str\n";4 });

bf503107f38c4b8c92006c7c.html

对于场景三,用来做尝试请求,请求失败后继续,若是成功则中止请求。用crontab也能解决,可是比较傻,好比设置每隔5分钟请求一次,无论成功会失败都会去执行一次。而用swoole定时器则智能多了。json

1 swoole_timer_tick(5*60*1000, function($timer) use ($url) { //启用定时器,每5分钟执行一次

2 $rs = $this->postUrl($url);3

4 if ($rs) {5 //业务代码...

6 swoole_timer_clear($timer); //中止定时器

7 echo date('Y-m-d H:i:s'). "请求接口任务执行成功\n";8 } else{9 echo date('Y-m-d H:i:s'). "请求接口失败,5分钟后再次尝试\n";10 }11 });

bf503107f38c4b8c92006c7c.html

示例代码

新建文件\src\App\Task.php:服务器

1 <?php2 namespace Helloweba\Swoole;3

4 useswoole_server;5

6 /**7 * 任务调度8 */

9 classTask10 {11 protected $serv;12 protected $host = '127.0.0.1';13 protected $port = 9506;14 //进程名称

15 protected $taskName = 'swooleTask';16 //PID路径

17 protected $pidPath = '/run/swooletask.pid';18 //设置运行时参数

19 protected $options =[20 'worker_num' => 4, //worker进程数,通常设置为CPU数的1-4倍

21 'daemonize' => true, //启用守护进程

22 'log_file' => '/data/log/swoole-task.log', //指定swoole错误日志文件

23 'log_level' => 0, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR

24 'dispatch_mode' => 1, //数据包分发策略,1-轮询模式

25 'task_worker_num' => 4, //task进程的数量

26 'task_ipc_mode' => 3, //使用消息队列通讯,并设置为争抢模式

27 ];28

29 public function __construct($options =[])30 {31 date_default_timezone_set('PRC');32 //构建Server对象,监听127.0.0.1:9506端口

33 $this->serv = new swoole_server($this->host, $this->port);34

35 if (!empty($options)) {36 $this->options = array_merge($this->options, $options);37 }38 $this->serv->set($this->options);39

40 //注册事件

41 $this->serv->on('Start', [$this, 'onStart']);42 $this->serv->on('Connect', [$this, 'onConnect']);43 $this->serv->on('Receive', [$this, 'onReceive']);44 $this->serv->on('Task', [$this, 'onTask']);45 $this->serv->on('Finish', [$this, 'onFinish']);46 $this->serv->on('Close', [$this, 'onClose']);47 }48

49 public functionstart()50 {51 //Run worker

52 $this->serv->start();53 }54

55 public function onStart($serv)56 {57 //设置进程名

58 cli_set_process_title($this->taskName);59 //记录进程id,脚本实现自动重启

60 $pid = "{$serv->master_pid}\n{$serv->manager_pid}";61 file_put_contents($this->pidPath, $pid);62 }63

64 //监听链接进入事件

65 public function onConnect($serv, $fd, $from_id)66 {67 $serv->send( $fd, "Hello {$fd}!");68 }69

70 //监听数据接收事件

71 public function onReceive(swoole_server $serv, $fd, $from_id, $data)72 {73 echo "Get Message From Client {$fd}:{$data}\n";74 //$this->writeLog('接收客户端参数:'.$fd .'-'.$data);

75 $res['result'] = 'success';76 $serv->send($fd, json_encode($res)); //同步返回消息给客户端

77 $serv->task($data); //执行异步任务

78 }79

80 /**81 * @param $serv swoole_server swoole_server对象82 * @param $task_id int 任务id83 * @param $from_id int 投递任务的worker_id84 * @param $data string 投递的数据85 */

86 public function onTask(swoole_server $serv, $task_id, $from_id, $data)87 {88 swoole_timer_tick(30000, function($timer) use ($task_id) { //启用定时器,每30秒执行一次

89 $memPercent = $this->getMemoryUsage();90 echo date('Y-m-d H:i:s') . '当前内存使用率:'.$memPercent."\n";91 });92 }93

94

95 /**96 * @param $serv swoole_server swoole_server对象97 * @param $task_id int 任务id98 * @param $data string 任务返回的数据99 */

100 public function onFinish(swoole_server $serv, $task_id, $data)101 {102 //103 }104

105

106 //监听链接关闭事件

107 public function onClose($serv, $fd, $from_id) {108 echo "Client {$fd} close connection\n";109 }110

111 public functionstop()112 {113 $this->serv->stop();114 }115

116 private functiongetMemoryUsage()117 {118 //MEMORY

119 if (false === ($str = @file("/proc/meminfo"))) return false;120 $str = implode("", $str);121 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);122 //preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buffers);

123

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

129 return $memPercent;130 }131 }

bf503107f38c4b8c92006c7c.html

咱们以场景一为例,在onTask启用定时任务,每隔30秒计算一次内存使用率。实际应用中能够把计算好的内存按时间写入数据库等存储中,而后能够根据前端需求用来渲染成统计图表,如:swoole

3c9042aeab1dca23b776637e73b24c21.pngbf503107f38c4b8c92006c7c.html

接着服务端代码 public\taskServer.php :

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

bf503107f38c4b8c92006c7c.html

客户端代码 public\taskClient.php :

{private $client;public function__construct() {$this->client = newswoole_client(SWOOLE_SOCK_TCP);

}public functionconnect() {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 = newClient();$client->connect();

bf503107f38c4b8c92006c7c.html

验证效果

1.启动服务端:

php taskServer.php

bf503107f38c4b8c92006c7c.html

2.客户端输入:

另开命令行窗口,执行

[root@localhost public]#php taskClient.php

请输入消息 Please input msg:hello

Get Message From Server:{"result":"success"}

[root@localhostpublic]#

bf503107f38c4b8c92006c7c.html

3.服务端返回:

b03aa679d7d72804f9665d1802f289cb.pngbf503107f38c4b8c92006c7c.html

若是返回上图中的结果,则定时任务正常运行,咱们会发现每隔30秒会输出一条信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值