Home PHP Framework Swoole php Swoole implements millisecond-level scheduled tasks

php Swoole implements millisecond-level scheduled tasks

Jan 25, 2020 pm 07:14 PM
php swoole

php Swoole implements millisecond-level scheduled tasks

During project development, if there are business requirements for scheduled tasks, we will use Linux's crontab to solve it, but its minimum granularity is minute level. If the required granularity is second level, Even at the millisecond level, crontab cannot satisfy it. Fortunately, swoole provides a powerful millisecond timer.

Recommended learning: swoole tutorial

Application scenario examples

We may encounter such a scenario:

● Scenario 1: Obtain the local memory usage every 30 seconds

● Scenario 2: Execute the report sending task after 2 minutes

● Scenario 3: Every day at 2 o'clock in the morning Request the third-party interface regularly. If the interface returns data, the task will be stopped. If the interface does not respond for some reason or no data is returned, continue to try to request the interface after 5 minutes. If it still fails after trying 5 times, stop the task

We can all summarize the above three scenarios into the category of scheduled tasks.

Swoole millisecond timer

Swoole provides an asynchronous millisecond timer function:

swoole_timer_tick(int $msec, callable $callback) : Set an interval clock timer and execute $callback every $msec milliseconds, similar to setInterval() in javascript.

swoole_timer_after(int $after_time_ms, mixed $callback_function): Execute $callback_function after the specified time $after_time_ms, similar to javascript setTimeout().

swoole_timer_clear(int $timer_id): Delete the timer with the specified id, similar to javascript's clearInterval().

Solution

For scenario one, it is often used in system detection statistics. The real-time requirements are relatively high, but the frequency can be controlled well. It is mostly used for background server performance. Monitoring can generate visual charts. The memory usage can be obtained once every 30 seconds, or every 10 seconds, but the minimum granularity of crontab can only be set to 1 minute.

 swoole_timer_tick(30000, function($timer) use ($task_id) { // 启用定时器,每30秒执行一次
     $memPercent = $this->getMemoryUsage(); //计算内存使用率
     echo date('Y-m-d H:i:s') . '当前内存使用率:'.$memPercent."\n";
 });
Copy after login

For scenario two, if you directly define a certain task after xx time, it seems that crontab is more difficult, but using swoole's swoole_timer_after can achieve:

 swoole_timer_after(120000, function() use ($str) { //2分钟后执行
     $this->sendReport(); //发送报表
     echo "send report, $str\n";
 });
Copy after login

For scenario three, it is used to make attempted requests. Continue after the request fails, and stop the request if it succeeds. It can also be solved using crontab, but it is rather silly. For example, if you set a request every 5 minutes, it will be executed regardless of success or failure. Using a swoole timer is much smarter.

swoole_timer_tick(5*60*1000, function($timer) use ($url) { // 启用定时器,每5分钟执行一次
      $rs = $this->postUrl($url);
  
      if ($rs) {
          //业务代码...
          swoole_timer_clear($timer); // 停止定时器
          echo date('Y-m-d H:i:s'). "请求接口任务执行成功\n";
      } else {
          echo date('Y-m-d H:i:s'). "请求接口失败,5分钟后再次尝试\n";
     }
 });
Copy after login

Sample code

New file\src\App\Task.php:

<?php 
namespace Helloweba\Swoole;

use swoole_server;

/**
* 任务调度
*/
class Task
{
    protected $serv;
    protected $host = &#39;127.0.0.1&#39;;
    protected $port = 9506;
    // 进程名称
    protected $taskName = &#39;swooleTask&#39;;
    // PID路径
    protected $pidPath = &#39;/run/swooletask.pid&#39;;
    // 设置运行时参数
    protected $options = [
        &#39;worker_num&#39; => 4, //worker进程数,一般设置为CPU数的1-4倍  
        &#39;daemonize&#39; => true, //启用守护进程
        &#39;log_file&#39; => &#39;/data/log/swoole-task.log&#39;, //指定swoole错误日志文件
        &#39;log_level&#39; => 0, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
        &#39;dispatch_mode&#39; => 1, //数据包分发策略,1-轮询模式
        &#39;task_worker_num&#39; => 4, //task进程的数量
        &#39;task_ipc_mode&#39; => 3, //使用消息队列通信,并设置为争抢模式
    ];

    public function __construct($options = [])
    {
        date_default_timezone_set(&#39;PRC&#39;); 
        // 构建Server对象,监听127.0.0.1:9506端口
        $this->serv = new swoole_server($this->host, $this->port);

        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $this->serv->set($this->options);

        // 注册事件
        $this->serv->on(&#39;Start&#39;, [$this, &#39;onStart&#39;]);
        $this->serv->on(&#39;Connect&#39;, [$this, &#39;onConnect&#39;]);
        $this->serv->on(&#39;Receive&#39;, [$this, &#39;onReceive&#39;]);
        $this->serv->on(&#39;Task&#39;, [$this, &#39;onTask&#39;]);  
        $this->serv->on(&#39;Finish&#39;, [$this, &#39;onFinish&#39;]);
        $this->serv->on(&#39;Close&#39;, [$this, &#39;onClose&#39;]);
    }

    public function start()
    {
        // Run worker
        $this->serv->start();
    }

    public function onStart($serv)
    {
        // 设置进程名
        cli_set_process_title($this->taskName);
        //记录进程id,脚本实现自动重启
        $pid = "{$serv->master_pid}\n{$serv->manager_pid}";
        file_put_contents($this->pidPath, $pid);
    }

    //监听连接进入事件
    public function onConnect($serv, $fd, $from_id)
    {
        $serv->send( $fd, "Hello {$fd}!" );
    }

    // 监听数据接收事件
    public function onReceive(swoole_server $serv, $fd, $from_id, $data)
    {
        echo "Get Message From Client {$fd}:{$data}\n";
        //$this->writeLog(&#39;接收客户端参数:&#39;.$fd .&#39;-&#39;.$data);
        $res[&#39;result&#39;] = &#39;success&#39;;
        $serv->send($fd, json_encode($res)); // 同步返回消息给客户端
        $serv->task($data);  // 执行异步任务
    }

    /**
    * @param $serv swoole_server swoole_server对象
    * @param $task_id int 任务id
    * @param $from_id 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(&#39;Y-m-d H:i:s&#39;) . &#39;当前内存使用率:&#39;.$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 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;
    }
}
Copy after login

We take scenario 1 as an example, enable scheduled tasks in onTask, and calculate memory usage every 30 seconds. In actual applications, the calculated memory can be written into a database or other storage based on time, and then used to render a statistical chart according to the front-end requirements, such as:

php Swoole implements millisecond-level scheduled tasks

Then the server side Code public\taskServer.php:

<?php 
require dirname(__DIR__) . &#39;/vendor/autoload.php&#39;;
use Helloweba\Swoole\Task;
$opt = [
    &#39;daemonize&#39; => false
];
$ser = new Task($opt);
$ser->start();
Copy after login

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 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();
Copy after login

Verification effect

1. Start the server:

php taskServer.php

2. Client input:

Open another command line window and execute

[root@localhost public]# php taskClient.php
Copy after login

Please input msg: hello

Get Message From Server:{"result":"success"}
[root@localhost public]#
Copy after login

3. The server returns:

php Swoole implements millisecond-level scheduled tasks

If the result in the above picture is returned, the scheduled task is running normally, and we will find that a message will be output every 30 seconds.

The above is the detailed content of php Swoole implements millisecond-level scheduled tasks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles