Home > php教程 > php手册 > 【转载】PHP使用1个crontab管理多个crontab任务

【转载】PHP使用1个crontab管理多个crontab任务

WBOY
Release: 2016-06-06 19:45:52
Original
949 people have browsed it

http://www.cnblogs.com/showker/archive/2013/09/01/3294279.html http://www.binarytides.com/php-manage-multiple-cronjobs-with-a-single-crontab-entry/ In many php applications there are multiple tasks that need to be run via cron at different

http://www.cnblogs.com/showker/archive/2013/09/01/3294279.html

 

http://www.binarytides.com/php-manage-multiple-cronjobs-with-a-single-crontab-entry/

 

In many php applications there are multiple tasks that need to be run via cron at different times. In a typical application you may be doing the following tasks via cronjobs : 

1. Backup database.
2. Send out email to subscribers.
3. Clear temporary files.
4. Fetch xml feeds from some source and store them in database.

So if you had separate php files doing these tasks , and had a cronjob entry for each , your cronjob could look like this :

MAILTO="happy@birthday.com"
0 0 * * * /var/www/my_app/backup_database.php
12 2 * * * /var/www/my_app/email_to_subscribers.php
10 5 * * * /var/www/my_app/clear_temp_files.php
10 7 * * * /var/www/my_app/fetch_xml_feeds.php

The above is the simplest approach to manage multiple cronjobs for your php application. However this approach has many drawbacks :

1. Multiple entries in crontabs means more time and effort needed to edit the crontab and maintain it.

- Since this approach involves writing each task separately in the cron list , it becomes difficult to maintain.

2. The crontab command has to be used everytime a change is to be made.

- You need to either manually do a `crontab -t` in the shell prompt or make your php application do it , everytime there is a change in either the tasks or their timing.

3. If the script name changes then have to edit the crontab file again.
4. A log email would be generated for every cron run, creating multiple log emails.

- Every task that is running would generate a cronlog and email itself to the email specified

5. Inefficient when there are 10s or 100s of tasks to be run via cron.

- Do you think it is a good idea if you had many many tasks to do.

An alternative solution

How about having only 1 entry in the cronjobs, and that 1 cronjob manages the rest of the cronjobs.

1. Add only 1 task to the crontab rule say :

<span>1</span> * * * * * php /path/to/cronjob.php
Copy after login

The cronjob.php file would run all the tasks that need to be run via cron. Its important to note that this cronjob.php will run every minute and forever. Do not be worried about it eating too much of system resources. It is a faily light thing and does not load your CPU or RAM with anything heavy.(注意这个cronjob.php会每分钟执行一次,而且一直会一直这样。不必担心这会消耗太多系统资源,这是一个非常轻量级的东西,它不会额外占用你的CPU和内存)

Now the next thing would be to make sure cronjob.php can run all the tasks at the right time.

2. Now we need to have different tasks have a different cron schedule. Lets say there are 3 different tasks to run at 3 different times :

0 5 * * * database_backup
0 5 1,15 * * monthly_sales_report
0 10 15 02 * purchase_report

Copy after login

 

The cronjob.php that runs every minute should have an array like this :

<span>1</span> <span>$cronjobs = array();
</span><span>2</span>  
<span>3</span> <span>$cronjobs['database_backup'] = '0 5 * * *';
</span><span>4</span> <span>$cronjobs['monthly_sales_report'] = '0 5 1,15 * *';
</span><span>5</span> $cronjobs['purchase_report'] = '0 10 15 02 *';
Copy after login

Now we test each job/task for the timestamp and run it like this :

<span>1</span> <span>foreach</span>(<span>$cronjobs</span> <span>as</span> <span>$method</span> => <span>$cron</span><span>)
</span><span>2</span> <span>{
</span><span>3</span>     <span>$time</span> = <span>time</span><span>();
</span><span>4</span>         <span>if</span>( is_time_cron(<span>$time</span> , <span>$cron</span><span>) )
</span><span>5</span> <span>    {
</span><span>6</span>         <span>$result</span> = <span>$method</span><span>();
</span><span>7</span>         <span>echo</span> <span>$result</span><span>;
</span><span>8</span> <span>    }
</span><span>9</span> }
Copy after login

is_time_cron checks if the current timestamp matches the cron schedule or not. If it matches , then the task is executed. Theis_time_cron method can be found in the previous post here.

In this approach the benefits are :

1. Only 1 crontab entry.

The crontab list is clean and your application does not overload it.

2. Easy to maintain , does not need any modification unless the script path/name changes.

The crontab once created does not need any change unless the name or path of 'cronjob.php' changes. Meanwhile the jobs inside cronjob.php can change their names , schedules and anything very easily.

3. To add/edit/remove tasks or change their time schedules only the cronjob.php needs to be changed.

This means easier modification , maintenance and the application can provide simple user interface to make changes anytime without the need to use crontab commands or anything as such.

The above mentioned approach can be applied to any language , not just php.

 

 

 

附加:判断当前时间蹉是否符合某个cronjob

http://www.binarytides.com/php-check-if-a-timestamp-matches-a-given-cron-schedule/

PHP check if a timestamp matches a given cron schedule

<span>1</span> <span>desktop:~$ php -a
</span><span>2</span> <span>Interactive shell
</span><span>3</span>  
<span>4</span> <span>php > echo time();
</span><span>5</span> <span>1319362432
</span><span>6</span> php > 
Copy after login

 

 

Above is an example of a given timestamp.

And a cron schedule can look like this 0 5 * * * - which means run everyday at 5 hours and 0 minutes.

Now in a php application you may need to test if a given timestamp , say 1319362432 matches a given cron schedule like 0 5 * * *.

Here is a quick php function that can do this task.

<span> 1</span> <span>/*</span><span>*
</span><span> 2</span> <span>    Test if a timestamp matches a cron format or not
</span><span> 3</span> <span>    //$cron = '5 0 * * *';
</span><span> 4</span> <span>*/</span>
<span> 5</span> <span>function</span> is_time_cron(<span>$time</span> , <span>$cron</span><span>) 
</span><span> 6</span> <span>{
</span><span> 7</span>     <span>$cron_parts</span> = <span>explode</span>(' ' , <span>$cron</span><span>);
</span><span> 8</span>     <span>if</span>(<span>count</span>(<span>$cron_parts</span>) != 5<span>)
</span><span> 9</span> <span>    {
</span><span>10</span>         <span>return</span> <span>false</span><span>;
</span><span>11</span> <span>    }
</span><span>12</span>      
<span>13</span>     <span>list</span>(<span>$min</span> , <span>$hour</span> , <span>$day</span> , <span>$mon</span> , <span>$week</span>) = <span>explode</span>(' ' , <span>$cron</span><span>);
</span><span>14</span>      
<span>15</span>     <span>$to_check</span> = <span>array</span>('min' => 'i' , 'hour' => 'G' , 'day' => 'j' , 'mon' => 'n' , 'week' => 'w'<span>);
</span><span>16</span>      
<span>17</span>     <span>$ranges</span> = <span>array</span><span>(
</span><span>18</span>         'min' => '0-59' ,
<span>19</span>         'hour' => '0-23' ,
<span>20</span>         'day' => '1-31' ,
<span>21</span>         'mon' => '1-12' ,
<span>22</span>         'week' => '0-6' ,
<span>23</span> <span>    );
</span><span>24</span>      
<span>25</span>     <span>foreach</span>(<span>$to_check</span> <span>as</span> <span>$part</span> => <span>$c</span><span>)
</span><span>26</span> <span>    {
</span><span>27</span>         <span>$val</span> = $<span>$part</span><span>;
</span><span>28</span>         <span>$values</span> = <span>array</span><span>();
</span><span>29</span>          
<span>30</span>         <span>/*</span>
<span>31</span> <span>            For patters like 0-23/2
</span><span>32</span>         <span>*/</span>
<span>33</span>         <span>if</span>(<span>strpos</span>(<span>$val</span> , '/') !== <span>false</span><span>)
</span><span>34</span> <span>        {
</span><span>35</span>             <span>//</span><span>Get the range and step</span>
<span>36</span>             <span>list</span>(<span>$range</span> , <span>$steps</span>) = <span>explode</span>('/' , <span>$val</span><span>);
</span><span>37</span>              
<span>38</span>             <span>//</span><span>Now get the start and stop</span>
<span>39</span>             <span>if</span>(<span>$range</span> == '*'<span>)
</span><span>40</span> <span>            {
</span><span>41</span>                 <span>$range</span> = <span>$ranges</span>[<span>$part</span><span>];
</span><span>42</span> <span>            }
</span><span>43</span>             <span>list</span>(<span>$start</span> , <span>$stop</span>) = <span>explode</span>('-' , <span>$range</span><span>);
</span><span>44</span>                  
<span>45</span>             <span>for</span>(<span>$i</span> = <span>$start</span> ; <span>$i</span> $stop ; <span>$i</span> = <span>$i</span> + <span>$steps</span><span>)
</span><span>46</span> <span>            {
</span><span>47</span>                 <span>$values</span>[] = <span>$i</span><span>;
</span><span>48</span> <span>            }
</span><span>49</span> <span>        }
</span><span>50</span>         <span>/*</span>
<span>51</span> <span>            For patters like :
</span><span>52</span> <span>            2
</span><span>53</span> <span>            2,5,8
</span><span>54</span> <span>            2-23
</span><span>55</span>         <span>*/</span>
<span>56</span>         <span>else</span>
<span>57</span> <span>        {
</span><span>58</span>             <span>$k</span> = <span>explode</span>(',' , <span>$val</span><span>);
</span><span>59</span>              
<span>60</span>             <span>foreach</span>(<span>$k</span> <span>as</span> <span>$v</span><span>)
</span><span>61</span> <span>            {
</span><span>62</span>                 <span>if</span>(<span>strpos</span>(<span>$v</span> , '-') !== <span>false</span><span>)
</span><span>63</span> <span>                {
</span><span>64</span>                     <span>list</span>(<span>$start</span> , <span>$stop</span>) = <span>explode</span>('-' , <span>$v</span><span>);
</span><span>65</span>                  
<span>66</span>                     <span>for</span>(<span>$i</span> = <span>$start</span> ; <span>$i</span> $stop ; <span>$i</span>++<span>)
</span><span>67</span> <span>                    {
</span><span>68</span>                         <span>$values</span>[] = <span>$i</span><span>;
</span><span>69</span> <span>                    }
</span><span>70</span> <span>                }
</span><span>71</span>                 <span>else</span>
<span>72</span> <span>                {
</span><span>73</span>                     <span>$values</span>[] = <span>$v</span><span>;
</span><span>74</span> <span>                }
</span><span>75</span> <span>            }
</span><span>76</span> <span>        }
</span><span>77</span>          
<span>78</span>         <span>if</span> ( !<span>in_array</span>( <span>date</span>(<span>$c</span> , <span>$time</span>) , <span>$values</span> ) and (<span>strval</span>(<span>$val</span>) != '*'<span>) ) 
</span><span>79</span> <span>        {
</span><span>80</span>             <span>return</span> <span>false</span><span>;
</span><span>81</span> <span>        }
</span><span>82</span> <span>    }
</span><span>83</span>      
<span>84</span>     <span>return</span> <span>true</span><span>;
</span><span>85</span> <span>}
</span><span>86</span>  
<span>87</span> <span>var_dump</span>(<span>time</span>() , '0 5 * * *');  <span>//</span><span>true or false</span>
Copy after login

How does it work

The above code uses the date format specifiers as follows :
'min' => 'i' ,
'hour' => 'G' ,
'day' => 'j' ,
'mon' => 'n' ,
'week' => 'w'

over the timestamp to extract the minute , hour , day , month and week of a timestamp

Then it checks the cron format by splitting it into parts like 0 , 5 , * , * , * and then tests each part for the corresponding value from timestamp.

 

效果:

crontab命令:

<span>1</span> * * * * * php /home/wwwroot/crontabs/cronjob.php
Copy after login

查看:

<span>1</span> crontab -l
Copy after login

编辑:

<span>1</span> crontab -e
Copy after login

参数:

<span> 1</span> <span>    5       *       *       *     *     ls             指定每小时的第5分钟执行一次ls命令
</span><span> 2</span> <span>    30     5       *        *     *     ls             指定每天的 5:30 执行ls命令
</span><span> 3</span> <span>    30     7       8        *     *     ls             指定每月8号的7:30分执行ls命令
</span><span> 4</span> <span>    30     5       8        6     *     ls             指定每年的6月8日5:30执行ls命令
</span><span> 5</span> <span>    30     6       *        *     0     ls             指定每星期日的6:30执行ls命令[注:0表示星期天,1表示星期1, 以此类推,也可以用英文来表示,sun表示星期天,mon表示星期一等。]
</span><span> 6</span> <span>    30     3     10,20      *     *     ls     每月10号及20号的3:30执行ls命令[注:“,”用来连接多个不连续的时段]
</span><span> 7</span> <span>    25     8-11     *       *     *     ls       每天8-11点的第25分钟执行ls命令[注:“-”用来连接连续的时段]
</span><span> 8</span> <span>    */15   *       *        *     *     ls         每15分钟执行一次ls命令 [即每个小时的第0 15 30 45 60分钟执行ls命令 ]
</span><span> 9</span> <span>    30     6     */10       *     *     ls       每个月中,每隔10天6:30执行一次ls命令[即每月的1、11、21、31日是的6:30执行一次ls 命令。 ]
</span><span>10</span>     50     7       *        *     *     root     run-parts     /etc/cron.daily   每天7:50以root 身份执行/etc/cron.daily目录中的所有可执行文件[ 注:run-parts参数表示,执行后面目录中的所有可执行文件。 ]
Copy after login

 

<span> 1</span> <span>$time</span> = <span>date</span>('YmdHi-s', <span>time</span><span>());
</span><span> 2</span> <span>$filename</span> = <span>$time</span> . '.txt'<span>;
</span><span> 3</span> <span>//</span><span>$fp = fopen("/home/wwwroot/crontabs/{$filename}", "w+"); //打开文件指针,创建文件
</span><span> 4</span> <span>//file_get_contents($fp,'sssss');</span>
<span> 5</span> <span>#</span><span>#####################################################################</span>
<span> 6</span> <span>$cronjobs</span> = <span>array</span><span>();
</span><span> 7</span> 
<span> 8</span> <span>$cronjobs</span>['database_backup'] = '*/2 * * * *'<span>;
</span><span> 9</span> <span>$cronjobs</span>['stttt'] = '*/3 * * * *'<span>;
</span><span>10</span> <span>$cronjobs</span>['monthly_sales_report'] = '0 5 1,15 * *'<span>;
</span><span>11</span> <span>$cronjobs</span>['purchase_report'] = '0 10 15 02 *'<span>;
</span><span>12</span> 
<span>13</span> 
<span>14</span> 
<span>15</span> 
<span>16</span> 
<span>17</span> <span>function</span><span> database_backup(){
</span><span>18</span>     <span>$r</span>=  <span>rand</span>(200, 9000<span>);
</span><span>19</span>     <span>$fp</span> = <span>fopen</span>("/home/wwwroot/crontabs/database_backup{<span>$r</span>}", "w+"); <span>//</span><span>打开文件指针,创建文件</span>
<span>20</span> <span>}
</span><span>21</span> <span>function</span><span> stttt(){
</span><span>22</span>     <span>$r</span>=  <span>rand</span>(200, 9000<span>);
</span><span>23</span>     <span>$fp</span> = <span>fopen</span>("/home/wwwroot/crontabs/stttt{<span>$r</span>}", "w+"); <span>//</span><span>打开文件指针,创建文件</span>
<span>24</span> }
Copy after login

【转载】PHP使用1个crontab管理多个crontab任务

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