PHP's scheduled task - Crontab


Crontab The most commonly used scheduling task management tool on Linux/UNIX systems. PHP developers will often use this tool in actual projects . However, limited by the actual project deployment and application environment, the editing of Crontab configuration information is mostly
operated by dedicated server maintenance personnel. Project users want to add and edit by themselves, and the process is cumbersome.
This chapter will develop a visual Crontab scheduled task management module based on the content management framework, which greatly
facilitates the use of developers and users.

1 Common Planned Task Implementation Methods
In actual development, we often encounter scenarios with planned task requirements, such as orders that are created but not paid, or
products that fail and need to be refunded, etc., which require certain operations to be performed regularly. There are many similar scenes. This section mainly explains
how to implement several common scheduled tasks.

1.1 PHP scripts implement scheduled tasks
Because PHP scripts run based on browsers, the program will automatically terminate after the browser is closed, and the maximum
execution defaulted to seconds, so in order for PHP scripts to implement scheduled tasks, one or Multiple scripts
can be executed all the time without depending on the operation of the browser. Common methods are given below.

Script execution time limit: Use PHP's built-in set_time_limit() method to allow the script to execute continuously.
set_time_limit(0); //By set me limit (0), the program can be executed indefinitely

When the browser is closed, the program does not terminate: use PHP's built-in ignore_user_abort() method to allow the script to continue executing when the browser is closed.
ignore_user_abort(); //Close the browser PHP script can also continue to execute

Script timing execution In order to prevent PHP from ending the process in advance, use the language built-in infinite loop structure and
sleep() waiting method to allow script timing execution, such as once every 5 seconds.
sleep($interval); //delay execution

A simple script example is given here to demonstrate the implementation process of PHP scheduled tasks. Create a new task.php file
, the implementation code is as follows:

<?php 
ignore_user_abort(); //Closing the browser PHP script can also continue to execute
set_time_limit(0); //By setting me limit (0), the program can be executed indefinitely
$interval = 3; //every 3 Second run
$number = 0; //counter
 
//infinite loop
do{ 
($number < 10) {     //execute file write operation     //timed write file     file_put_contents( _DIR_.'/log/log'.date( 'Ymd_His').'.log',time()) ;      $number =$number+1 ;      sleep($interval); //delay execution }while(true) ; 





 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In the above code, the code in the loop is executed once per second, and the scheduled task (new
log file) is executed 10 times in total. Note the two system methods defined in the script header file, the code is as follows:

ignore_user_abort(); //Close the browser PHP script can also continue to execute
set_time_limit(0); //The program can be executed indefinitely through set me limit (0)
1
2
Access the task.php script in the browser, you can It is found that in the lo directory, 10 log files will be added automatically,

However, if you use this method, if you update the content of the PHP file, you need to restart the PHP process to make the scheduled task
take effect. In addition, if there is a program error or memory overflow, the process currently running in PHP will also be terminated, so using this
method is extremely unstable and inconvenient to maintain.

1.2 Use system-level scheduled task tools Since using PHP scripts to implement scheduled tasks is not ideal in some aspects, it is a better choice
to use external tools .
Whether it is Windows or Linux operating system, there are complete solutions for scheduled tasks.
For example, in Windows 10, in the control panel, you can directly find the task scheduler and manage scheduled tasks. It is
relatively simple to use.


However, based on the PHP project, it is generally less deployed on the Windows server, so the Crontab scheduled task command tool in the Linux system is the most commonly used by PHP developers
. After successful login, execute the following command to view the help information of Crontab.

The results of crontab -h
1 are as follows

You can also execute the following command to see what accounting tasks the administrator user ( root ) has.

The execution results of crontab -l
1 are as follows

In fact, no matter which scheduled task tool is used, it is to realize the function of executing a certain task at a specific time.

2. Introduction to Crontab
The Crontab scheduled task tool on Linux does not have a visual interactive interface. Both configuration and use of the tool need to be
operated on the command line. This section mainly explains some input operations of the Cron tab tool.

2.1 Crontab usage tutorial
Before talking about it, you need to understand the difference between Cron and Crontab. The frequently used Crontab command
is the abbreviation of the combination of Cron and Table. It is actually a Cron configuration file, and it can also be used as a job list. Developers can
define different time expressions to achieve different task requirements.
Cron is a Linux system process, and Cron can execute specific scheduled tasks with Shell scripts.

Taking ubun 16.04 as an example, Cron tab has configuration files in multiple places in the system.

/var/spool/cron/crontabs: This directory stores the Crontab of each user, and the configuration file is consistent with the user name.
/etc/cron.d/: Store the Crontab files or scripts that need to be executed.
/etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron. monthly: The scripts in these directories can be executed once per hour, per day, per week, and per month.
Commonly used commands are as follows:
crontab [- u username) //Omitting the user table means operating the cron tab of the current user

e Edit task list)
1 List commands in task list)
r Delete task list)
Crontab's commands are composed of: time expression + operator + operation command.
There are five types of time expressions: minute, hour, day, month, and week, and the operators are as follows:

*: All numbers within the value range
/: Every number of numbers
-: From x to z
.: Hash number For example: execute the command `showtima` every minute The example is as follows: `* * * * * showtima`
1
2
3
4
Execute a certain PHP script file every day 30 An example is as follows

 30 23 * * * /usr/bin/php7.0 /var/www/task.php
1
The meaning of the time expression is very flexible, but if it is not used frequently, it is easy to cause configuration. It is recommended to use the
online Crontab-style generator here, according to Customization is required. The access address is: http://www pppet.net
After visiting, the effect will be used


2.2 Crontab Realizes Regular Writing of PHP Files
For the convenience of demonstration, here is a function of writing the file date every minute. First,
add the log.php file body code in the /var/www (Ubun virtual machine environment) directory of the system as follows

<?php 
file_put_contents(__DIR__.'/run.log',date("Ymd H:i:s")."\r\n",FILE_APPEND); ?> 1 2 3 Every time this  
script
is
executed
,
a A file with current time information to distinguish when the file was created
Then execute the following command to add a Cronta expression to the current user and specify when to execute the log.php script

crontab -e
1
adds the following:

* * * * * /use/bin/php7.0 /var/www/log.php
1
Wait for a few minutes after saving, and find that the run.log file is automatically generated in the /var/www directory, and use the cat
command to view it. The content is as follows

root@scotchbox:/var/www# cat run.log
2018-01-03 16:01:01 
2018-03-03 16:02:01 
2018-03-03 16:03:02  
1
2
3
4
according to Crontab The configured time task expression, the log.php script will be executed every one minute, and if the
script file is modified at this time, there is no need to restart the PHP process. The modified code is as follows:

<?php 
file_put_contents(__DIR__.'/run.log',"time:".date("Ymd H:i:s")."\r\n",FILE_APPEND); ?>  
1
2
3
minutes
passed Wait, check the ru log file again, and find that the new format content has been written

2018-01-03 16:01:01 
2018-03-03 
16:02:01 2018-03-03 16:03:02 
2018-01-03 16:04:01 
time:2018 01-03 16 : 05 : 01
1
2
3
4
5
Through careful observation of the log list, it can be found that when Crontab is executed, the default minimum unit is "minute",
and it will start from the first second (according to the time edited by the configuration file, the error is within 2 seconds) implement. Developers can also
use the sleep keyword to define when to execute in 1 second, and the modified time expression is as follows:

* * * * * sleep 20; /use/bin/php7.0 /var/www/log.php
1
The parameter 20 after sleep refers to how many seconds to delay the execution. After waiting for a few minutes, check the run.log file again.
It was found that the time when the file was written has changed:

2018-03-03 16:03:02 
2018-01-03 16:04:01 
time:2018 01-03 16:05:01
time:2018 01-03 16:06:01
time:2018 01-03 16: 07:01
time: 2018 01-03 16:08: 01
time: 2018 01-03 16:10: 21
time: 2018 01-03 16:11: 21
1
2
3
4
5
6
7
8
strange knowledge
completed After the development of the scheduled task display list management, the user can define the required task content by himself, but if he wants to
run it automatically, he also needs an automatic task execution script to manage these tasks. In fact, the steps are as follows.

1. Install third-party dependent class libraries

In order to improve development efficiency, two dependent class libraries are mainly installed here, which are used to parse Crontab expressions and send
HTTP requests. In the root directory of the project, the command to install mtdowling/cron-expression is as follows:

composer require mtdowling/cron-expression 
1
In order to better obtain the HTTP return value of the request URL address, install the rmccue/requests command
as follows

composer require rmccue/requests
1
2. Develop core task scripts
In order to better manage the code, add the crontab application module under the project application directory, and
add the Crontask.php controller file under the controller directory under this module. The development task execution script in this file
is as follows.
(1) Add an initialization method. In order to prevent misuse, this script can only be operated under the command line. In the Crontask controller file, add the following code

/*
*Initialization configuration list
@var array 
*/
private $_config = [] ;
/*
*Initialization method
*/
public function _initialize(} {     parent::_initialize();     config('app_trace', false); //close app_trace     //Can only be executed in cli mode     if(!$this->request- >isCli()){         $this->error("Scheduled tasks must be executed on the command line");     }     //Initialization status     $this- >_config=[     'DELETE'=>-1,//Deleted'DISABLED     '=>0,//     Disabled'NORMAL'=>1,//Normal     'COMPLETED'=>2,//Completed'EXPIRED     ' =>3,//Expired     ] }













    


 
 
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 17 18 19 20 21 22 23 24 25 26 27 28 For the stable execution of the script,
the code forcibly closes the Trace output mode that comes with the framework, and prohibits Any way to run this script in command line mode. Its code is as follows:













    config('app_trace', false) ; //Close app_trace
if(!$this->request->isCli()){         $this->error("Scheduled tasks must be executed on the command line");     } 1 2 3 4 5 (2) Realize the core method of task management. Add the index() method in the controller and add the following code







/**
*Timed task execution method
*@return bool 
**/
public function index(){     //Query all task lists     $map['status']= ['>', 0];      $crontab_list = Db:: name("crontab ")->where ($map)->select();     if(!$crontab_list){             return false;     }     $now_time =time();     foreach($crontab_list as $key =>$cromtab){         $is_execute = false ; //Whether to execute         $update =[];//Data that needs to be updated          if($now_time<$cromtab["begin_time"]){              continue;//The task has not started to skip          }           if($cromtab[ "maximums"] && $cromtab["executes"]>=$cromtab["maximums"]){














                 $update["status"]=$this->config["COMPLETED"];//The task exceeds the maximum number of executions and the task is completed} 
         elseif($cromtab["end_time"] >0 && $now_time> $cromtab["end_time" ] ){              $update["status "]=$this->config["EXPIRED"];// task expires          }else{                 //expression when creating scheduled task object and passing in                 $cron = CronExpression:: factory($crontab['schedule']);                 if($cron->isDue()){                     //allow execution                     $is_execute = true;                      //update status when execution is allowed                     $update["execute_time"]= $now_time;                      $update["update_time"]= $now_time;                     $update["executes"]=$crontab["executes"]+ 1;
 











                     $update["status"]= ($crontab["maximums"]>0 && $update["executes"]>=$update["maximums"]?$this->config["COMPLETED"]:$this- >config["NORMAL"];
                     )else{                          //If the time is not up, skip this task to judge the next task                          continue;                       }                 }                   $map= [] ;                       $map["id"]= $crontab["id "];                      Db::name("crontab")-> where($map)->update($update);                      //Use the flag bit to judge whether the execution condition is met (whether the task starts, whether the specified number of times has not been reached, etc.) Finally decide whether to execute the task or just update the task status                      if(! $is_execute){                          continue;                      }else{










//Execute scheduled task operation
try{ 
        //Judge task type
        switch($crontab['type']){             //Request URL             case "url"                 if(substr($crontab["content"] ,0,1)== "/"){                     //local url                 $request = shell_exec("php".__ROOT_PATH__."index.php".$crontab["content"]."2>&1"); //modify log}                 else                 {                     // The remote URL uses curl to request                         //modify the log                 }                 break;             case "shell"                 $request = shell_exec($crontab["content"]."2>&1");                     //Modify log                     break;






                



                    






        
        }
        }catch(\Execeptionm $e){                 log exception

        }
 
    }
}
—————————————————
Copyright statement: This article is an original article of CSDN blogger "Extreme Dream Network Worry-free", following the CC 4.0 BY-SA copyright agreement, please attach The link to the source of the original text and this statement.
Original link: https://blog.csdn.net/wangzhae/article/details/115019692

Guess you like

Origin blog.csdn.net/qq_31432773/article/details/130724451