Home > php教程 > php手册 > 纯PHP实现定时器任务(Timer),php实现定时器timer

纯PHP实现定时器任务(Timer),php实现定时器timer

WBOY
Release: 2016-06-13 08:57:02
Original
1073 people have browsed it

纯PHP实现定时器任务(Timer),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()函数,详细介绍请查阅官网.

实现原理    

  用一个三维数组保存所有需要执行的任务,一级索引为时间戳,值为执行任务的方法、回调参数等,具体数组形式如下:

 

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

  这些任务可以是任意类的方法。既然是定时任务,我们需要一个类似计时的东东,此方案采用信号量去做,每一秒向当前进程发送SIGALRM信号,并捕获该信号,触发信号处理函数,循环遍历数据,判断是否有当前时间需要执行的任务。如果有则采用回调方式触发,并把参数传递给该方法。

<span>  1</span> <?<span>php
</span><span>  2</span> <span>/*</span><span>*
</span><span>  3</span> <span>*定时器
</span><span>  4</span> <span>*/</span>
<span>  5</span> <span>class</span><span> Timer
</span><span>  6</span> <span>{
</span><span>  7</span>     <span>//</span><span>保存所有定时任务</span>
<span>  8</span>     <span>public</span> <span>static</span> <span>$task</span> = <span>array</span><span>();
</span><span>  9</span> 
<span> 10</span>         <span>//</span><span>定时间隔</span>
<span> 11</span>         <span>public</span> <span>static</span> <span>$time</span> = 1<span>;
</span><span> 12</span> 
<span> 13</span>         <span>/*</span><span>*
</span><span> 14</span> <span>    *开启服务
</span><span> 15</span> <span>        *@param $time int
</span><span> 16</span>        <span>*/</span>
<span> 17</span>     <span>public</span> <span>static</span> <span>function</span> run(<span>$time</span> = <span>null</span><span>)
</span><span> 18</span> <span>        {
</span><span> 19</span>         <span>if</span>(<span>$time</span><span>)
</span><span> 20</span> <span>            {
</span><span> 21</span>                     self::<span>$time</span> = <span>$time</span><span>;
</span><span> 22</span> <span>            }
</span><span> 23</span>             self::<span>installHandler();
</span><span> 24</span>             pcntl_alarm(1<span>);
</span><span> 25</span> <span>         }
</span><span> 26</span>         <span>/*</span><span>*
</span><span> 27</span> <span>        *注册信号处理函数
</span><span> 28</span>         <span>*/</span>
<span> 29</span>         <span>public</span> <span>static</span> <span>function</span><span> installHandler()
</span><span> 30</span> <span>        {
</span><span> 31</span>             pcntl_signal(SIGALRM, <span>array</span>('Timer','signalHandler'<span>));
</span><span> 32</span> <span>        }
</span><span> 33</span> 
<span> 34</span>         <span>/*</span><span>*
</span><span> 35</span> <span>        *信号处理函数
</span><span> 36</span>         <span>*/</span>
<span> 37</span>         <span>public</span> <span>static</span> <span>function</span><span> signalHandler()
</span><span> 38</span> <span>        {
</span><span> 39</span>             self::<span>task();
</span><span> 40</span>         <span>//</span><span>一次信号事件执行完成后,再触发下一次</span>
<span> 41</span>         pcntl_alarm(self::<span>$time</span><span>);
</span><span> 42</span> <span>        }
</span><span> 43</span> 
<span> 44</span>         <span>/*</span><span>*
</span><span> 45</span> <span>        *执行回调
</span><span> 46</span>         <span>*/</span>
<span> 47</span>         <span>public</span> <span>static</span> <span>function</span><span> task()
</span><span> 48</span> <span>        {
</span><span> 49</span>             <span>if</span>(<span>empty</span>(self::<span>$task</span><span>))
</span><span> 50</span>             {<span>//</span><span>没有任务,返回</span>
<span> 51</span>                     <span>return</span><span> ;
</span><span> 52</span> <span>            }
</span><span> 53</span>             <span>foreach</span>(self::<span>$task</span> <span>as</span> <span>$time</span> => <span>$arr</span><span>)
</span><span> 54</span> <span>        {
</span><span> 55</span>                     <span>$current</span> = <span>time</span><span>();
</span><span> 56</span>         
<span> 57</span>                 <span>foreach</span>(<span>$arr</span> <span>as</span> <span>$k</span> => <span>$job</span><span>)
</span><span> 58</span>             {<span>//</span><span>遍历每一个任务</span>
<span> 59</span>                         <span>$func</span> = <span>$job</span>['func'];    <span>/*</span><span>回调函数</span><span>*/</span>
<span> 60</span>                         <span>$argv</span> = <span>$job</span>['argv'];    <span>/*</span><span>回调函数参数</span><span>*/</span>
<span> 61</span>                 <span>$interval</span> = <span>$job</span>['interval'];    <span>/*</span><span>时间间隔</span><span>*/</span>
<span> 62</span>                         <span>$persist</span> = <span>$job</span>['persist'];    <span>/*</span><span>持久化</span><span>*/</span>
<span> 63</span> 
<span> 64</span>                         <span>if</span>(<span>$current</span> == <span>$time</span><span>)
</span><span> 65</span>                         {<span>//</span><span>当前时间有执行任务
</span><span> 66</span> 
<span> 67</span> <span>                    //调用回调函数,并传递参数</span>
<span> 68</span>                                <span>call_user_func_array</span>(<span>$func</span>, <span>$argv</span><span>);
</span><span> 69</span>                     
<span> 70</span>                     <span>//</span><span>删除该任务</span>
<span> 71</span>                             <span>unset</span>(self::<span>$task</span>[<span>$time</span>][<span>$k</span><span>]);
</span><span> 72</span> <span>                        }
</span><span> 73</span>                         <span>if</span>(<span>$persist</span><span>)
</span><span> 74</span>                         {<span>//</span><span>如果做持久化,则写入数组,等待下次唤醒</span>
<span> 75</span>                                self::<span>$task</span>[<span>$current</span>+<span>$interval</span>][] = <span>$job</span><span>;
</span><span> 76</span> <span>                        }
</span><span> 77</span> <span>            }
</span><span> 78</span>             <span>if</span>(<span>empty</span>(self::<span>$task</span>[<span>$time</span><span>]))
</span><span> 79</span> <span>            {
</span><span> 80</span>                 <span>unset</span>(self::<span>$task</span>[<span>$time</span><span>]);
</span><span> 81</span> <span>            }
</span><span> 82</span> <span>            }
</span><span> 83</span> <span>        }
</span><span> 84</span> 
<span> 85</span>         <span>/*</span><span>*
</span><span> 86</span> <span>        *添加任务
</span><span> 87</span>         <span>*/</span>
<span> 88</span>         <span>public</span> <span>static</span> <span>function</span> add(<span>$interval</span>, <span>$func</span>, <span>$argv</span> = <span>array</span>(), <span>$persist</span> = <span>false</span><span>)
</span><span> 89</span> <span>        {
</span><span> 90</span>             <span>if</span>(<span>is_null</span>(<span>$interval</span><span>))
</span><span> 91</span> <span>            {
</span><span> 92</span>                 <span>return</span><span>;
</span><span> 93</span> <span>            }
</span><span> 94</span>             <span>$time</span> = <span>time</span>()+<span>$interval</span><span>;
</span><span> 95</span>         <span>//</span><span>写入定时任务</span>
<span> 96</span>         self::<span>$task</span>[<span>$time</span>][] = <span>array</span>('func'=><span>$func</span>, 'argv'=><span>$argv</span>, 'interval'=><span>$interval</span>, 'persist'=><span>$persist</span><span>);
</span><span> 97</span> <span>        }
</span><span> 98</span> 
<span> 99</span>         <span>/*</span><span>*
</span><span>100</span> <span>        *删除所有定时器任务
</span><span>101</span>         <span>*/</span>
<span>102</span>         <span>public</span> <span>function</span><span> dellAll()
</span><span>103</span> <span>        {
</span><span>104</span>             self::<span>$task</span> = <span>array</span><span>();
</span><span>105</span> <span>        }
</span><span>106</span> }
Copy after login

  这是定时器类核心部分,有一个静态变量保存有所有需要执行的任务,这里为什么是静态的呢?大家自行思考.当进程接受到 SIGALRM 信号后,触发 signalHandler 函数,随后循序遍历数组查看是否有当前时间需要执行的任务,有则回调,并传递参数,删除当前job,随后检查是否要做持久化任务,是则继续将当前job写入事件数组等待下次触发,最后再为当前进程设置一个闹钟信号.可以看出这个定时器,只要触发一次就会从内部再次触发,得到自循环目的.

<span> 1</span> <?<span>php
</span><span> 2</span> 
<span> 3</span> <span>class</span><span> DoJob
</span><span> 4</span> <span>{
</span><span> 5</span>     <span>public</span> <span>function</span> job( <span>$param</span> = <span>array</span><span>() )
</span><span> 6</span> <span>    {
</span><span> 7</span>         <span>$time</span> = <span>time</span><span>();
</span><span> 8</span>         <span>echo</span> "Time: {<span>$time</span>}, Func: ".<span>get_class</span>()."::".<span>__FUNCTION__</span>."(".json_encode(<span>$param</span>).")\n"<span>;
</span><span> 9</span> <span>    }
</span><span>10</span> }
Copy after login

  这是回调类及函数,为方便说明,加入不少调试信息.Timer类及回调都有了,我们看看使用场景是怎么样的.

<span> 1</span> <?<span>php
</span><span> 2</span> 
<span> 3</span> <span>require_once</span>(__DIR__."/Timer.php"<span>);
</span><span> 4</span> <span>require_once</span>(__DIR__."/DoJob.php"<span>);
</span><span> 5</span> 
<span> 6</span> 
<span> 7</span> Timer::<span>dellAll();
</span><span> 8</span> 
<span> 9</span> Timer::add( 1, <span>array</span>('DoJob','job'), <span>array</span>(),<span>true</span><span>);
</span><span>10</span> 
<span>11</span> Timer::add( 3, <span>array</span>('DoJob','job'),<span>array</span>('a'=>1), <span>false</span><span>);
</span><span>12</span> 
<span>13</span> <span>echo</span> "Time start: ".<span>time</span>()."\n"<span>;
</span><span>14</span> Timer::<span>run();
</span><span>15</span> 
<span>16</span> <span>while</span>(1<span>)
</span><span>17</span> <span>{
</span><span>18</span>     <span>sleep</span>(1<span>);
</span><span>19</span> <span>    pcntl_signal_dispatch();
</span><span>20</span> }
Copy after login

  代码非常短,这里注册了两个job,随后运行定时器,在一个无限循环里捕捉信号触发动作,如果不捕获将无法触发事先注册的处理函数.这样一个自循环的定时器开发完成.运行结果如下:

  

  如我们场景类添加的任务一样,在90的时候执行了两个任务,一个为持久化的不带参数的job,一个为非持久化带参数的job,随后非持久化job不再执行.

总结

  • 在收到信号前,当前进程不能退出.这里我使用了条件永远为真的循环.在我们实际生产环境中,需要创造这么一个先决条件,比如说,我们有一组服务,这些服务都是一直运行的,不管是IO访问,等待socket链接等等,当前服务都不会终止,即使进程阻塞也不会有问题,这种场景,也就是有一个一直运行的服务中使用.
  • 目前PHP只支持以秒为单位的触发,不支持更小时间单位,对位定时任务而言基本足够
Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template