Home > Article > Backend Development > PHP scheduled task implementation and Linux crontab scheduled task
Sometimes in order to monitor a certain program, a scheduled task is needed. The program needs to run automatically.
1. ignore_user_abort()
ignore_user_abort() function can be used with set_time_limit(0) and sleep($interval) to realize automatic program running and updating.
Example:
//Even if the Client is disconnected (such as closing the browser), the PHP script can continue to execute.
ignore_user_abort();
//The execution time is unlimited, and the default execution time of PHP is 30 seconds, through set_time_limit(0), the program can be executed without limit
set_time_limit(0);
// Run every 5 minutes
$interval=60*5;
do{
$url = "http://yaolei.info";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setop t($ch , CURLOPT_TIMEOUT, 2);
$result = curl_exec($ch);
curl_close($ch);
// Wait for 5 minutes
sleep($interval);
}while(true);
Just run the page above and then close it, the program will keep running.
2. crontab
There is a simpler method under Linux, which is the crontab command. The function of the crontab command is to schedule the execution of some commands at a certain time interval.
crontab usage: crontab [ -e | -l | -r ] file name -e: edit task -l: display task information -r: delete scheduled execution task information
crontab format:
* * * * * Command
Example of crontab command to run in time, day, month and week: