| 
                         // 监听数据接收事件    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 $fromid 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 connectionn";    } 
public function stop()    {      $this->serv->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启用定时任务,每隔30秒计算一次内存使用率。实际应用中可以把计算好的内存按时间写入数据库等存储中,然后可以根据前端需求用来渲染成统计图表,如: 
接着服务端代码 publictaskServer.php: 
<?php require dirname(__DIR__) . '/vendor/autoload.php';  use HellowebaSwooleTask;  $opt = [    'daemonize' => false  ];  $ser = new Task($opt);  $ser->start(); 
客户端代码 publictaskClient.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使用Swoole实现毫秒级定时任务的方法的文章就介绍到这了,更多相关php Swoole实现毫秒级定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!                         (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |