当前位置:网站首页>Implementation of PHP multitask second timer
Implementation of PHP multitask second timer
2022-07-26 05:58:00 【lxw1844912514】
1. describe
Recently deployed in the company crontab When , Whether the sudden whim can be used PHP To implement a timer , It's good if the particle size reaches the second level , because crontab Up to minute level , At the same time, I also investigated and used PHP There aren't too many timers to implement ,Swoole It is extended to realize a millisecond timer, which is very efficient , But after all, it's not pure PHP It's written in code , So finally, consider using PHP To implement a timer class , For learning reference .
2. Code implementation
When implementing timer code , Yes PHP Two extensions of the system
Pcntl - Multi process extension :
Mainly let PHP Many child processes can be started at the same time , Handle some tasks in parallel .
Spl - SplMinHeap - Small cap pile
A small top heap data structure , When implementing the timer , The efficiency of this structure is good , Insert 、 The time complexity of deletion is O(logN) , image libevent The timer is also 1.4 This data structure was adopted after the version, and before that rbtree, If you use a linked list or a fixed array , Insert... Every time 、 Deleting may require re traversal or sorting , There are still some performance problems .
3. technological process

explain
1、 Define timer structure , What parameters are there .
2、 Then register all of them into our timer class Timer.
3、 Call the timer class monitor Method , Start listening .
4、 The monitoring process is a while Dead cycle , Keep looking to see if the top of the time pile has expired , Originally, I thought about watching it every second , Later, when I thought about looking at it every second, I still had a problem , If it happens to be us sleep(1) The timer has expired , Then we can't implement it accurately right away , There may be a risk of delay , So we still use usleep(1000) Millisecond level to see and can also suspend the process to reduce CPU load .
4. Code
<?php
/**** Class Timer*/
class Timer extends SplMinHeap
{
/**
* Compare the size of the root node and the newly inserted node
* @param mixed $value1
* @param mixed $value2
* @return int
*/
protected function compare($value1, $value2)
{
if ($value1['timeout'] > $value2['timeout']) {
return -1;
}
if ($value1['timeout'] < $value2['timeout']) {
return 1;
}
return 0;
}
/**
* Insert node
* @param mixed $value
*/
public function insert($value)
{
$value['timeout'] = time() + $value['expire'];
parent::insert($value);
}
/**
* monitor
* @param bool $debug
*/
public function monitor($debug = false)
{
while (!$this->isEmpty()) {
$this->exec($debug);
usleep(1000);
}
}
/**
* perform
* @param $debug
*/
private function exec($debug)
{
$hit = 0;
$t1 = microtime(true);
while (!$this->isEmpty()) {
$node = $this->top();
if ($node['timeout'] <= time()) { // Out of the pile or into the pile
$node['repeat'] ? $this->insert($this->extract()) : $this->extract();
$hit = 1; // Start subprocess
if (pcntl_fork() == 0) {
empty($node['action']) ? '' : call_user_func($node['action']);
exit(0);
}
// Ignore child processes , Subprocess exit is recycled by the system
pcntl_signal(SIGCLD, SIG_IGN);
} else {
break;
}
}
$t2 = microtime(true);
echo ($debug && $hit) ? ' Time pile - Adjustment time : ' . round($t2 - $t1, 3) . " second \r\n" : '';
}
}5. example
<?php
$timer = new Timer();
// register - 3s - Repeat trigger
$timer->insert(array('expire' => 3, 'repeat' => true, 'action' => function () {
echo '3 second - repeat - hello world' . "\r\n";
}));
// register - 3s - Repeat trigger
$timer->insert(array('expire' => 3, 'repeat' => true, 'action' => function () {
echo '3 second - repeat - gogo' . "\r\n";
}));
// register - 6s - Trigger once
$timer->insert(array('expire' => 6, 'repeat' => false, 'action' => function () {
echo '6 second - once - hello xxxx' . "\r\n";
}));
// monitor
$timer->monitor(false)6. Execution results

Related articles
Linux Crontab Timed mission details
php Swoole Achieve millisecond level scheduled tasks
How to use well swoole Millisecond timer function ?
linux Delete regularly N Documents before ( Folder )

边栏推荐
- Introduction to Chinese text error correction task
- ament_cmake生成ROS2库并链接
- Redis持久化-RDB
- 解决Vagrant报错b:48:in `join‘: incompatible character encodings: GBK and UTF-8 (Encoding::Compatib
- 语法泛化三种可行方案介绍
- 字节面试题——判断一棵树是否为平衡二叉树
- Practice operation and maintenance knowledge accumulation
- Flex layout
- Redis发布订阅
- MBA-day28 数的概念-练习题
猜你喜欢

"Recursive processing of subproblems" -- judging whether two trees are the same tree -- and the subtree of another tree

金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十一))

Recursive processing - subproblem

【Oracle SQL】计算同比与环比(列转行进行偏移)

idea yml 文件代码不提示解决方案

Modifiers should be declared in the correct order 修饰符应按正确的顺序声明

Ros2 knowledge: DDS basic knowledge

平衡二叉树(AVL) ~

Redis持久化-AOF

日志收集分析平台搭建-1-环境准备
随机推荐
程序员如何改善精神内耗?
ERROR: Could not open requirements file: [Errno 2] No such file or directory: ‘requirments.txt’
Sequential search, half search, block search~
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十一))
Benji Banas launched the second season of earn while playing bonus activities, supporting the use of multiple Benji passes!
Who is responsible for the problems of virtual idol endorsement products? And listen to the lawyer's analysis
Redis transaction
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十))
平衡二叉树(AVL) ~
Redis publish subscription
MBA-day28 数的概念-练习题
Jdbc流式查询与游标查询
Knowledge precipitation I: what does an architect do? What problems have been solved
The time complexity of two recursive entries in a recursive function
Can you make a JS to get the verification code?
ES Cluster in Red status: what about write & delete operations?
光量子里程碑:6分钟内解决3854个变量问题
Kingbasees SQL language reference manual of Jincang database (8. Function (10))
顺序查找,折半查找,分块查找 ~
Blurring of unity pixel painting