【转载】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> }

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











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
