Inhaltsverzeichnis
An alternative solution
PHP check if a timestamp matches a given cron schedule
效果:
Heim php教程 php手册 【转载】PHP使用1个crontab管理多个crontab任务

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

Jun 06, 2016 pm 07:45 PM
crontab php 任务 使用 多个 管理

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
Nach dem Login kopieren

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

Nach dem Login kopieren

 

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 *';
Nach dem Login kopieren

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> }
Nach dem Login kopieren

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 > 
Nach dem Login kopieren

 

 

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>
Nach dem Login kopieren

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
Nach dem Login kopieren

查看:

<span>1</span> crontab -l
Nach dem Login kopieren

编辑:

<span>1</span> crontab -e
Nach dem Login kopieren

参数:

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

 

<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> }
Nach dem Login kopieren

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

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

Repo: Wie man Teamkollegen wiederbelebt
1 Monate vor By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
2 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Abenteuer: Wie man riesige Samen bekommt
1 Monate vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

CakePHP-Projektkonfiguration CakePHP-Projektkonfiguration Sep 10, 2024 pm 05:25 PM

In diesem Kapitel werden wir die Umgebungsvariablen, die allgemeine Konfiguration, die Datenbankkonfiguration und die E-Mail-Konfiguration in CakePHP verstehen.

PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 bringt mehrere neue Funktionen, Sicherheitsverbesserungen und Leistungsverbesserungen mit einer beträchtlichen Menge an veralteten und entfernten Funktionen. In dieser Anleitung wird erklärt, wie Sie PHP 8.4 installieren oder auf PHP 8.4 auf Ubuntu, Debian oder deren Derivaten aktualisieren. Obwohl es möglich ist, PHP aus dem Quellcode zu kompilieren, ist die Installation aus einem APT-Repository wie unten erläutert oft schneller und sicherer, da diese Repositorys in Zukunft die neuesten Fehlerbehebungen und Sicherheitsupdates bereitstellen.

CakePHP Datum und Uhrzeit CakePHP Datum und Uhrzeit Sep 10, 2024 pm 05:27 PM

Um in cakephp4 mit Datum und Uhrzeit zu arbeiten, verwenden wir die verfügbare FrozenTime-Klasse.

CakePHP-Datei hochladen CakePHP-Datei hochladen Sep 10, 2024 pm 05:27 PM

Um am Datei-Upload zu arbeiten, verwenden wir den Formular-Helfer. Hier ist ein Beispiel für den Datei-Upload.

CakePHP-Routing CakePHP-Routing Sep 10, 2024 pm 05:25 PM

In diesem Kapitel lernen wir die folgenden Themen im Zusammenhang mit dem Routing kennen.

Besprechen Sie CakePHP Besprechen Sie CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP ist ein Open-Source-Framework für PHP. Es soll die Entwicklung, Bereitstellung und Wartung von Anwendungen erheblich vereinfachen. CakePHP basiert auf einer MVC-ähnlichen Architektur, die sowohl leistungsstark als auch leicht zu verstehen ist. Modelle, Ansichten und Controller gu

CakePHP erstellt Validatoren CakePHP erstellt Validatoren Sep 10, 2024 pm 05:26 PM

Der Validator kann durch Hinzufügen der folgenden zwei Zeilen im Controller erstellt werden.

So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein Dec 20, 2024 am 11:31 AM

Visual Studio Code, auch bekannt als VS Code, ist ein kostenloser Quellcode-Editor – oder eine integrierte Entwicklungsumgebung (IDE) –, die für alle gängigen Betriebssysteme verfügbar ist. Mit einer großen Sammlung von Erweiterungen für viele Programmiersprachen kann VS Code c

See all articles