Table of Contents
How to use pure PHP to implement timer tasks (Timer), timer timer
Home Backend Development PHP Tutorial How to use pure PHP to implement timer tasks (Timer), timer timer_PHP tutorial

How to use pure PHP to implement timer tasks (Timer), timer timer_PHP tutorial

Jul 13, 2016 am 09:45 AM
php php language

How to use pure PHP to implement timer tasks (Timer), timer timer

Timer tasks are common in WEB applications, how to use PHP to implement timer tasks, roughly Two options: 1) Use the Crontab command to write a shell script, call the PHP file in the script, and then execute the script regularly; 2) Use ignore_user_abort() and set_time_limit() to run the script without the browser. The former uses the characteristics of Linux and has little to do with PHP itself. The latter has limited usage scenarios and can only trigger the script with one HTTP request and exit after execution. So how do we use pure PHP to implement pure timer tasks and adapt to the business needs of cognitive tasks?

Basic knowledge

This program is developed under Linux and runs in cli mode. Here is a brief introduction to the basic knowledge.

CLI: PHP’s command line mode, common WEB applications use fpm;
Process: Process is the basic unit of program running. Processes run independently without interfering with each other. They have independent running space and each process has a process control block;
Inter-process communication: Since the process runs independently, we need a mechanism to ensure the exchange of information between different processes. Inter-process communication mainly includes: pipes, IPC (shared memory, signals, message queues), sockets ;
PCNTL extension: A process extension of PHP, which mainly uses the pcntl_alarm() function. Please refer to the official website for detailed introduction.

Principle of implementation  

Use a three-dimensional array to save all tasks that need to be executed. The first-level index is the timestamp, and the value is the method of executing the task, callback parameters, etc. The specific array form is as follows:

array(
  '1438156396' => array(
    array(1,array('Class','Func'), array(), true), 
  )
)
说明:
1438156396 时间戳
array(1,array('Class','Func'), array(), true) 
参数依次表示: 执行时间间隔,回调函数,传递给回调函数的参数,是否持久化(ture则一直保存在数据中,否则执行一次后删除)

Copy after login

These tasks can be methods of any class. Since it is a scheduled task, we need something similar to timing. This solution uses a semaphore to send the SIGALRM signal to the current process every second, capture the signal, trigger the signal processing function, loop through the data, and determine whether there is a current time required to perform the task. If so, use a callback to trigger it and pass the parameters to the method.

<&#63;php
 /**
 *定时器
 */
 class Timer
 {
  //保存所有定时任务
  public static $task = array();
 
   //定时间隔
   public static $time = 1;
 
   /**
  *开启服务
   *@param $time int
   */
  public static function run($time = null)
   {
   if($time)
    {
      self::$time = $time;
    }
    self::installHandler();
    pcntl_alarm(1);
   }
   /**
   *注册信号处理函数
   */
   public static function installHandler()
   {
    pcntl_signal(SIGALRM, array('Timer','signalHandler'));
   }
 
   /**
   *信号处理函数
   */
   public static function signalHandler()
   {
    self::task();
   //一次信号事件执行完成后,再触发下一次
   pcntl_alarm(self::$time);
   }
 
   /**
   *执行回调
   */
   public static function task()
   {
    if(empty(self::$task))
    {//没有任务,返回
      return ;
    }
    foreach(self::$task as $time => $arr)
   {
      $current = time();
   
     foreach($arr as $k => $job)
    {//遍历每一个任务
       $func = $job['func']; /*回调函数*/
       $argv = $job['argv']; /*回调函数参数*/
     $interval = $job['interval']; /*时间间隔*/
       $persist = $job['persist']; /*持久化*/
 
       if($current == $time)
       {//当前时间有执行任务
 
      //调用回调函数,并传递参数
         call_user_func_array($func, $argv);
      
      //删除该任务
        unset(self::$task[$time][$k]);
       }
       if($persist)
       {//如果做持久化,则写入数组,等待下次唤醒
         self::$task[$current+$interval][] = $job;
       }
    }
    if(empty(self::$task[$time]))
    {
     unset(self::$task[$time]);
    }
    }
   }
 
   /**
   *添加任务
   */
   public static function add($interval, $func, $argv = array(), $persist = false)
   {
    if(is_null($interval))
    {
     return;
    }
    $time = time()+$interval;
   //写入定时任务
   self::$task[$time][] = array('func'=>$func, 'argv'=>$argv, 'interval'=>$interval, 'persist'=>$persist);
   }
 
   /**
   *删除所有定时器任务
   */
   public function dellAll()
   {
    self::$task = array();
   }
 }

Copy after login

This is the core part of the timer class. There is a static variable that stores all the tasks that need to be performed. Why is it static here? Think about it for yourself. When the process receives the SIGALRM signal, the signalHandler function is triggered, and then the array is traversed sequentially. Check whether there are tasks that need to be executed at the current time. If there are any tasks that need to be executed at the current time, call back and pass parameters to delete the current job. Then check whether a persistent task is to be done. If so, continue to write the current job into the event array and wait for the next trigger. Finally, the current job will be deleted. The process sets an alarm signal. It can be seen that this timer, as long as it is triggered once, will be triggered again from the inside, achieving the purpose of self-loop.

<&#63;php
 
 class DoJob
 {
  public function job( $param = array() )
  {
   $time = time();
   echo "Time: {$time}, Func: ".get_class()."::".__FUNCTION__."(".json_encode($param).")\n";
  }
 }
Copy after login

 

This is the callback class and function. For the convenience of explanation, a lot of debugging information has been added. The Timer class and callback are available. Let’s see what the usage scenario is like.

<&#63;php
 
 require_once(__DIR__."/Timer.php");
 require_once(__DIR__."/DoJob.php");
 
 
 Timer::dellAll();
 
 Timer::add( 1, array('DoJob','job'), array(),true);
 
 Timer::add( 3, array('DoJob','job'),array('a'=>1), false);
 
 echo "Time start: ".time()."\n";
 Timer::run();
 
 while(1)
 {
  sleep(1);
  pcntl_signal_dispatch();
 }
Copy after login

The code is very short. Two jobs are registered here, and then the timer is run to capture the signal triggering action in an infinite loop. If it is not captured, the pre-registered processing function will not be triggered. Such a self-loop timer has been developed. .The running results are as follows:

Just like the tasks added by our scene class, two tasks were executed at 90, one is a persistent job without parameters, and the other is a non-persistent job with parameters, and then the non-persistent job is no longer Execute.

Summary

1. The current process cannot exit before receiving the signal. Here I use a loop whose condition is always true. In our actual production environment, we need to create such a prerequisite. For example, we have a set of services, these The service is always running. Whether it is IO access, waiting for socket connection, etc., the current service will not be terminated. Even if the process is blocked, there will be no problem. This scenario is used in a service that is always running.
2. Currently, PHP only supports triggering in seconds and does not support smaller time units, which is basically sufficient for scheduled tasks

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1041338.htmlTechArticleHow to use pure PHP to implement timer tasks (Timer), timer timer timer tasks, which are common in WEB applications , how to use PHP to implement timer tasks, there are roughly two options: 1) Use...
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

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 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

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

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 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