search
HomeBackend DevelopmentPHP TutorialHow 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

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则一直保存在数据中,否则执行一次后删除)

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();
   }
 }

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";
  }
 }

 

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();
 }

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
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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor