当前位置:网站首页>How to use PHP spoole to implement millisecond scheduled tasks
How to use PHP spoole to implement millisecond scheduled tasks
2022-07-02 09:26:00 【Yisu cloud】
How to use php Swoole Achieve millisecond scheduled tasks
This article mainly introduces how to use php Swoole Achieve millisecond scheduled tasks , It has certain reference value , Interested friends can refer to , I hope you will gain a lot after reading this article , Now let Xiaobian take you to know .
Project under development , If there are business requirements for scheduled tasks , We will use linux Of crontab To solve , But its minimum granularity is minute , If the granularity is required to be second , Even millisecond level ,crontab Can't be satisfied , thankfully swoole Powerful millisecond timer provided .
Examples of application scenarios
We may encounter such a scene :
Scene one : every other 30 Get the local memory usage rate once per second
Scene two :2 Execute the report sending task in minutes
Scene three : Every morning 2 Request the third-party interface at o'clock , If the interface returns data, stop the task , If the interface does not respond or does not return data for some reason 5 Continue to try to request the interface after minutes , Try 5 If it still fails after times, stop the task
The above three scenarios can be summarized into the category of timed tasks .
Swoole Millisecond timer
Swoole Provides asynchronous millisecond timer function :
swoole_timer_tick(int $msec, callable $callback): Set an interval clock timer , every other $msec Execute in milliseconds $callback, Be similar to javascript Medium setInterval().
swoole_timer_after(int $after_time_ms, mixed $callback_function): At the appointed time $after_time_ms After execution $callback_function, Be similar to javascript Of setTimeout().
swoole_timer_clear(int $timer_id): Delete the specified id Timer for , Be similar to javascript Of clearInterval().
Solution
For scenario 1 , It is often used in system detection and statistics , The real-time requirement is relatively high , But it can control the frequency , Mostly used in the background The server Performance monitoring , Visual charts can be generated . It can be 30 Get the memory usage rate once per second , It can also be 10 second , and crontab The minimum granularity can only be set to 1 minute .
swoole_timer_tick(30000, function($timer) use ($task_id) { // Enable timer , Every time 30 Once per second
$memPercent = $this->getMemoryUsage(); // Calculate memory usage
echo date('Y-m-d H:i:s') . ' Current memory usage :'.$memPercent."\n";
});For scenario two , Direct definition xx If you perform a task after time , Looks like crontab More difficult , While using swoole Of swoole_timer_after Can achieve :
swoole_timer_after(120000, function() use ($str) { //2 Execute in minutes
$this->sendReport(); // Send report
echo "send report, $str\n";
});For scenario three , Used to make an attempt request , Continue after the request fails , If successful, stop the request . use crontab Can also solve , But it's stupid , For example, set every 5 One minute request , Whether it succeeds or fails, it will be implemented once . While using swoole Timers are much more intelligent .
swoole_timer_tick(5*60*1000, function($timer) use ($url) { // Enable timer , Every time 5 Once per minute
$rs = $this->postUrl($url);
if ($rs) {
// Business code ...
swoole_timer_clear($timer); // Stop timer
echo date('Y-m-d H:i:s'). " The request interface task was successfully executed \n";
} else {
echo date('Y-m-d H:i:s'). " Request interface failed ,5 Try again in minutes \n";
}
});Sample code
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 route
protected $pidPath = '/run/swooletask.pid';
// Set run-time parameters
protected $options = [
'worker_num' => 4, //worker Number of processes , Generally set as CPU Count 1-4 times
'daemonize' => true, // Enable daemons
'log_file' => '/data/log/swoole-task.log', // Appoint swoole Error log file
'log_level' => 0, // The level of logging The scope is 0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
'dispatch_mode' => 1, // Packet distribution strategy ,1- Polling mode
'task_worker_num' => 4, //task The number of processes
'task_ipc_mode' => 3, // Use message queuing to communicate , And set it to scramble mode
];
public function __construct($options = [])
{
date_default_timezone_set('PRC');
// structure Server object , monitor 127.0.0.1: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 events
$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 the process name
cli_set_process_title($this->taskName);
// Record the process id, The script realizes automatic restart
$pid = "{$serv->master_pid}\\n{$serv->manager_pid}";
file_put_contents($this->pidPath, $pid);
}
// Listen for connection entry events
public function onConnect($serv, $fd, $from_id)
{
$serv->send( $fd, "Hello {$fd}!" );
}
// Listen for data receiving events
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)); // The synchronization returns a message to the client
$serv->task($data); // Perform asynchronous tasks
}
/**
* @param $serv swoole_server swoole_server object
* @param $task_id int Mission id
* @param $from\id int Delivering tasks worker_id
* @param $data string Posted data
*/
public function onTask(swoole_server $serv, $task_id, $from_id, $data)
{
swoole_timer_tick(30000, function($timer) use ($task_id) { // Enable timer , Every time 30 Once per second
$memPercent = $this->getMemoryUsage();
echo date('Y-m-d H:i:s') . ' Current memory usage :'.$memPercent."\n";
});
}
/**
* @param $serv swoole_server swoole_server object
* @param $task_id int Mission id
* @param $data string The data returned by the task
*/
public function onFinish(swoole_server $serv, $task_id, $data)
{
//
}
// Listen for connection close events
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 , stay onTask Enable scheduled tasks , every other 30 Calculate the memory usage every second . In practical application, the calculated memory can be written into the database and other storage by time , Then it can be used to render statistical charts according to the front-end requirements , Such as :

Then the server code public\taskServer.php :
<?php require dirname(__DIR__) . '/vendor/autoload.php'; use Helloweba\Swoole\Task; $opt = [ 'daemonize' => false ]; $ser = new Task($opt); $ser->start();
Client code 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 enter a message 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();Verification effect
1. Start server :
php taskServer.php
2. Client input :
Open another command line window , perform
[[email protected] public]# php taskClient.php
Please enter a message Please input msg:hello
Get Message From Server:{"result":"success"}
[[email protected] public]#3. Server return :

If the result in the above figure is returned , Then the scheduled task runs normally , We will find that every 30 Seconds will output a message .
Thank you for reading this article carefully , Hope Xiaobian can share “ How to use php Swoole Achieve millisecond scheduled tasks ” This article is helpful to you , At the same time, I hope you can support Yisu cloud more , Pay attention to Yisu cloud industry information channel , More relevant knowledge is waiting for you to learn !
边栏推荐
- [go practical basis] how to bind and use URL parameters in gin
- Flink-使用流批一体API统计单词数量
- Jingdong senior engineer has developed for ten years and compiled "core technology of 100 million traffic website architecture"
- Redis安装部署(Windows/Linux)
- A detailed explanation takes you to reproduce the statistical learning method again -- Chapter 2, perceptron model
- Supplier selection and prequalification of Oracle project management system
- WSL installation, beautification, network agent and remote development
- Probability is not yet. Look at statistical learning methods -- Chapter 4, naive Bayesian method
- [staff] time sign and note duration (full note | half note | quarter note | eighth note | sixteenth note | thirty second note)
- 西瓜书--第六章.支持向量机(SVM)
猜你喜欢

数构(C语言--代码有注释)——第二章、线性表(更新版)

Matplotlib swordsman Tour - an artist tutorial to accommodate all rivers

During MySQL installation, mysqld Exe reports that the application cannot start normally (0xc000007b)`

Don't spend money, spend an hour to build your own blog website
![[go practical basis] gin efficient artifact, how to bind parameters to structures](/img/c4/44b3bda826bd20757cc5afcc5d26a9.png)
[go practical basis] gin efficient artifact, how to bind parameters to structures

西瓜书--第五章.神经网络

Probability is not yet. Look at statistical learning methods -- Chapter 4, naive Bayesian method

I've taken it. MySQL table 500W rows, but someone doesn't partition it?

Statistical learning methods - Chapter 5, decision tree model and learning (Part 1)

Redis installation and deployment (windows/linux)
随机推荐
数构(C语言)——第四章、矩阵的压缩存储(下)
Statistical learning methods - Chapter 5, decision tree model and learning (Part 1)
Watermelon book -- Chapter 5 neural network
Data type case of machine learning -- using data to distinguish men and women based on Naive Bayesian method
【Go实战基础】gin 如何验证请求参数
The channel cannot be viewed when the queue manager is running
Troubleshooting and handling of an online problem caused by redis zadd
Timed thread pool implements request merging
Cloudrev self built cloud disk practice, I said that no one can limit my capacity and speed
Chrome视频下载插件–Video Downloader for Chrome
Dix ans d'expérience dans le développement de programmeurs vous disent quelles compétences de base vous manquez encore?
WSL installation, beautification, network agent and remote development
Micro service practice | introduction and practice of zuul, a micro service gateway
AMQ 4043 solution for errors when using IBM MQ remote connection
Learn combinelatest through a practical example
企业级SaaS CRM实现
"Interview high frequency question" is 1.5/5 difficult, and the classic "prefix and + dichotomy" application question
十年开发经验的程序员告诉你,你还缺少哪些核心竞争力?
ORA-12514问题解决方法
Knife4j 2. Solution to the problem of file control without selection when uploading x version files