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

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

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


 

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 *';

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

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 > 

 

 

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>

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

查看:

<span>1</span> crontab -l

编辑:

<span>1</span> crontab -e

参数:

<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参数表示,执行后面目录中的所有可执行文件。 ]

 

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

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

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment