Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use php Swoole to schedule tasks in millisecond timing

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use php Swoole to achieve millisecond timing planning tasks, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

In project development, if there are business requirements for timing tasks, we will use linux's crontab to solve them, but its minimum granularity is minutes. If the granularity required is seconds, or even milliseconds, crontab cannot meet it. Fortunately, the powerful millisecond timer provided by swoole.

Examples of application scenarios

We may encounter a scenario like this:

Scenario 1: get the local memory utilization every 30 seconds

Scenario 2: execute the report sending task in 2 minutes

Scenario 3: request the third-party interface regularly at 2 o'clock every morning, and stop the task if the interface returns data. If the interface does not respond or does not return data for some reason, continue to try to request the interface after 5 minutes. If you still fail after 5 attempts, stop the task.

The above three scenarios can be summarized into the category of scheduled tasks.

Swoole millisecond timer

Swoole provides asynchronous millisecond timer functions:

Swoole_timer_tick (int $msec, callable $callback): sets an interval clock timer to execute $callback every $msec millisecond, similar to setInterval () in javascript.

Swoole_timer_after (int $after_time_ms, mixed $callback_function): executes $callback_function after the specified time $after_time_ms, similar to javascript's setTimeout ().

Swoole_timer_clear (int $timer_id): removes the timer for the specified id, similar to javascript's clearInterval ().

Solution

For scenario 1, it is often used in system detection and statistics, which requires high real-time performance, but can control the frequency. It is mostly used for background server performance monitoring and can generate visual charts. Memory usage can be obtained once in 30 seconds or 10 seconds, while the minimum granularity of crontab can only be set to 1 minute.

Swoole_timer_tick (30000, function ($timer) use ($task_id) {/ / enables the timer and executes $memPercent = $this- > getMemoryUsage () every 30 seconds; / / calculates the memory usage echo date ('Y-m-d HavaVISS'). 'current memory usage:'. $memPercent. "\ n";})

For scenario 2, if you directly define the xx time to perform a task, it seems that crontab is more difficult, but the swoole_timer_after of swoole can be implemented:

Swoole_timer_after (120000, function () use ($str) {/ / execute $this- > sendReport () in 2 minutes; / / send report echo "send report, $str\ n";})

For scenario 3, it is used to make an attempt request, continue after the request fails, and stop the request if it succeeds. It can also be solved with crontab, but it's silly, such as setting a request every 5 minutes, regardless of success or failure. Using swoole timers is much smarter.

Swoole_timer_tick (5 / 60 / 1000, function ($timer) use ($url) {/ / enable timer, execute $rs = $this- > postUrl ($url) every 5 minutes; if ($rs) {/ / business code. Swoole_timer_clear ($timer); / / stop the timer echo date ('Y-m-d Havi echo date'). "the request interface task was successfully executed\ n";} else {echo date ('Y-m-d Hrigi echo date'). "failed to request interface. Try again 5 minutes later";}})

Sample code

Create a new file\ src\ App\ Task.php:

Namespace Helloweba\ Swoole; use swoole_server; / * Task scheduling * / class Task {protected $serv; protected $host = '127.0.0.1'; protected $port = 9506; / / process name protected $taskName = 'swooleTask'; / / PID path protected $pidPath =' / run/swooletask.pid' / / set the runtime parameter protected $options = ['worker_num' = > 4, / / the number of worker processes, generally set to 1-4 times the number of CPU' daemonize' = > true, / / enable daemons' log_file' = >'/ data/log/swoole-task.log', / / specify swoole error log file 'log_level' = > 0, / / log level range is 0-5. 1While TRACEPERROR 'dispatch_mode' = > 1, / / packet distribution strategy, 1-polling mode' task_worker_num' = > 4, / / number of task processes' task_ipc_mode' = > 3, / / using message queuing to communicate and set to contention mode] Public function _ construct ($options = []) {date_default_timezone_set ('PRC'); / / build a Server object that listens to 127.0.0.1 options 9506 port $this- > serv = new swoole_server ($this- > host, $this- > port); if (! empty ($options)) {$this- > options = array_merge ($this- > options, $options);} $this- > serv- > set ($this- > options) / Registration event $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) {/ / set process name cli_set_process_title ($this- > taskName) / / record the process id, and the script automatically restarts $pid = "{$serv- > master_pid}\ n {$serv- > manager_pid}"; file_put_contents ($this- > pidPath, $pid);} / / listen for connection entry event public function onConnect ($serv, $fd, $from_id) {$serv- > send ($fd, "Hello {$fd}!") } / / listen to the data receiving event public function onReceive (swoole_server $serv, $fd, $from_id, $data) {echo "Get Message From Client {$fd}: {$data}\ n"; / / $this- > writeLog ('receive client parameters:'. $fd.'-. $data); $res ['result'] =' success'; $serv- > send ($fd, json_encode ($res)) / / synchronously returns a message to the client $serv- > task ($data) / / execute asynchronous task} / * * @ param $serv swoole_server swoole_server object * @ param $task_id int task id * @ param $from\ id int delivery task worker_id * @ param $data string delivered data * / public function onTask (swoole_server $serv, $task_id, $from_id, $data) {swoole_timer_tick (30000) Function ($timer) use ($task_id) {/ / enable timer Execute $memPercent = $this- > getMemoryUsage () every 30 seconds Echo date ('Y-m-d Hrigi'). 'current memory usage:'. $memPercent. "\ n";}) } / * * @ param $serv swoole_server swoole_server object * @ param $task_id int task id * @ param $data string task returned data * / public function onFinish (swoole_server $serv, $task_id, $data) {/ / listen connection close event 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;}}

Let's take scenario 1 as an example, enable scheduled tasks in onTask, and calculate memory usage every 30 seconds. In practical applications, the calculated memory can be written into database and other storage according to time, and then can be rendered into statistical charts according to the needs of the frontend, such as:

Then the server code public\ taskServer.php:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report