纯PHP实现定时器任务(Timer)
定时器任务,在WEB应用比较常见,如何使用PHP实现定时器任务,大致有两种方案:1)使用Crontab命令,写一个shell脚本,在脚本中调用PHP文件,然后定期执行该脚本;2)配合使用ignore_user_abort()和set_time_limit(),使脚本脱离浏览器运行。前者是利用Linux的特性,和PHP本身没有多大关系,后者使用场景有限,且只能由一次HTTP请求触发该脚本,执行完后退出。那么我们如何使用纯PHP实现纯粹的定时器任务,且能适应认识任务业务需求?
基础知识
此程序在Linux下开发,以cli模式运行,一下是基本知识的简要介绍。
CLI:PHP的命令行模式,常见的WEB应用使用的是fpm;
进程:进程是程序运行的基本单元,进程之间是独立运行且互不干扰的,有独立的运行空间,每个进程都有一个进程控制块;
进程间通信:既然进程是独立运行,我们需要一种机制保证不同进程信息的交换,进程间通信主要包括:管道,IPC(共享内存,信号,消息队列),套接字;
PCNTL扩展:PHP的一个进程扩展,主要用到pcntl_alarm()函数,详细介绍请查阅官网.
实现原理
用一个三维数组保存所有需要执行的任务,一级索引为时间戳,值为执行任务的方法、回调参数等,具体数组形式如下:
array( '1438156396' => array( array(1,array('Class','Func'), array(), true), ) ) 说明: 1438156396 时间戳 array(1,array('Class','Func'), array(), true) 参数依次表示: 执行时间间隔,回调函数,传递给回调函数的参数,是否持久化(ture则一直保存在数据中,否则执行一次后删除)
这些任务可以是任意类的方法。既然是定时任务,我们需要一个类似计时的东东,此方案采用信号量去做,每一秒向当前进程发送SIGALRM信号,并捕获该信号,触发信号处理函数,循环遍历数据,判断是否有当前时间需要执行的任务。如果有则采用回调方式触发,并把参数传递给该方法。
1 <?php 2 /** 3 *定时器 4 */ 5 class Timer 6 { 7 //保存所有定时任务 8 public static $task = array(); 9 10 //定时间隔 11 public static $time = 1; 12 13 /** 14 *开启服务 15 *@param $time int 16 */ 17 public static function run($time = null) 18 { 19 if($time) 20 { 21 self::$time = $time; 22 } 23 self::installHandler(); 24 pcntl_alarm(1); 25 } 26 /** 27 *注册信号处理函数 28 */ 29 public static function installHandler() 30 { 31 pcntl_signal(SIGALRM, array('Timer','signalHandler')); 32 } 33 34 /** 35 *信号处理函数 36 */ 37 public static function signalHandler() 38 { 39 self::task(); 40 //一次信号事件执行完成后,再触发下一次 41 pcntl_alarm(self::$time); 42 } 43 44 /** 45 *执行回调 46 */ 47 public static function task() 48 { 49 if(empty(self::$task)) 50 {//没有任务,返回 51 return ; 52 } 53 foreach(self::$task as $time => $arr) 54 { 55 $current = time(); 56 57 foreach($arr as $k => $job) 58 {//遍历每一个任务 59 $func = $job['func']; /*回调函数*/ 60 $argv = $job['argv']; /*回调函数参数*/ 61 $interval = $job['interval']; /*时间间隔*/ 62 $persist = $job['persist']; /*持久化*/ 63 64 if($current == $time) 65 {//当前时间有执行任务 66 67 //调用回调函数,并传递参数 68 call_user_func_array($func, $argv); 69 70 //删除该任务 71 unset(self::$task[$time][$k]); 72 } 73 if($persist) 74 {//如果做持久化,则写入数组,等待下次唤醒 75 self::$task[$current+$interval][] = $job; 76 } 77 } 78 if(empty(self::$task[$time])) 79 { 80 unset(self::$task[$time]); 81 } 82 } 83 } 84 85 /** 86 *添加任务 87 */ 88 public static function add($interval, $func, $argv = array(), $persist = false) 89 { 90 if(is_null($interval)) 91 { 92 return; 93 } 94 $time = time()+$interval; 95 //写入定时任务 96 self::$task[$time][] = array('func'=>$func, 'argv'=>$argv, 'interval'=>$interval, 'persist'=>$persist); 97 } 98 99 /** 100 *删除所有定时器任务 101 */ 102 public function dellAll() 103 { 104 self::$task = array(); 105 } 106 }
这是定时器类核心部分,有一个静态变量保存有所有需要执行的任务,这里为什么是静态的呢?大家自行思考.当进程接受到 SIGALRM 信号后,触发 signalHandler 函数,随后循序遍历数组查看是否有当前时间需要执行的任务,有则回调,并传递参数,删除当前job,随后检查是否要做持久化任务,是则继续将当前job写入事件数组等待下次触发,最后再为当前进程设置一个闹钟信号.可以看出这个定时器,只要触发一次就会从内部再次触发,得到自循环目的.
1 <?php 2 3 class DoJob 4 { 5 public function job( $param = array() ) 6 { 7 $time = time(); 8 echo "Time: {$time}, Func: ".get_class()."::".__FUNCTION__."(".json_encode($param).")\n"; 9 } 10 }
这是回调类及函数,为方便说明,加入不少调试信息.Timer类及回调都有了,我们看看使用场景是怎么样的.
1 <?php 2 3 require_once(__DIR__."/Timer.php"); 4 require_once(__DIR__."/DoJob.php"); 5 6 7 Timer::dellAll(); 8 9 Timer::add( 1, array('DoJob','job'), array(),true); 10 11 Timer::add( 3, array('DoJob','job'),array('a'=>1), false); 12 13 echo "Time start: ".time()."\n"; 14 Timer::run(); 15 16 while(1) 17 { 18 sleep(1); 19 pcntl_signal_dispatch(); 20 }
代码非常短,这里注册了两个job,随后运行定时器,在一个无限循环里捕捉信号触发动作,如果不捕获将无法触发事先注册的处理函数.这样一个自循环的定时器开发完成.运行结果如下:
如我们场景类添加的任务一样,在90的时候执行了两个任务,一个为持久化的不带参数的job,一个为非持久化带参数的job,随后非持久化job不再执行.
总结
在收到信号前,当前进程不能退出.这里我使用了条件永远为真的循环.在我们实际生产环境中,需要创造这么一个先决条件,比如说,我们有一组服务,这些服务都是一直运行的,不管是IO访问,等待socket链接等等,当前服务都不会终止,即使进程阻塞也不会有问题,这种场景,也就是有一个一直运行的服务中使用.
目前PHP只支持以秒为单位的触发,不支持更小时间单位,对位定时任务而言基本足够

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using
