Home > Article > Backend Development > What are the methods to implement scheduled tasks in PHP?
php methods to implement scheduled tasks are: 1. Use the crontab under the Linux system to implement; 2. Use the ignore_user_abort function to implement; 3. Use the file_get_contents function to implement.
1. Server scheduled tasks
Server scheduled tasks are actually under unix systems crontab implementation, specific settings: Linux scheduled task crontab; however, in addition to directly reading PHP scripts regularly, we can also use scheduled interface calls.
(Learning video recommendation: java video tutorial)
When running the script:
*/1 * * * * php /data/www/cron.php Execute cron.php every minute
URL mode call:
lynx mode:*/1 * * * * lynx -dump http://www. xxxxxxx.com/cron.php (-dump option to convert the URL output to standard output)
curl method: */1 * * * * /usr/bin/curl -o temp.txt http: //www.xxxxxxx.com/cron.php (Curl displays output on standard output by default. Use the "curl -o" option to dump the output of the script to the temporary file temp.txt)
wget method: */1 * * * * /usr/bin/wget -q -O temp.txt http://www.xxxxxxx.com/cron.php (the q option indicates quiet mode. "-O temp.txt" indicates that the output will Send to a temporary file.)
The above method is to place the php script in an address that can be accessed using a URL, such as http://www.xxxxxx.com/cron.php, and call the trigger task regularly.
2. ignore_user_abort() method
ignore_user_abort() function sets whether disconnecting from the client will terminate the execution of the script.
First use a cron.php file to control the termination of the script. The content of cron.php is:
<?php return 1; ?>
The script php file is:
<?php ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行. set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去 $interval=60*30;// 每隔半小时运行 do{ $run = include 'config.php'; if(!$run) die('process abort'); //return 0 时, 终止 //TODO 该干啥干啥 sleep($interval);// 等待5分钟 } while(true);
By changing the cron.php return 0 , to stop the program. But this method is not good at memory management.
3. file_get_contents() method
<?php $time=15; $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //TODO sleep($time); file_get_contents($url); ?>
php script sleep continues to execute after a period of time by accessing itself. This ensures that the execution time of each PHP script will not be too long and will not be affected by time_out limit. Because each loop of the php file is executed independently, this method avoids the time_out limit. But it is best to add the control code cron.php as above so that the process can be terminated.
Related recommendations: php training
The above is the detailed content of What are the methods to implement scheduled tasks in PHP?. For more information, please follow other related articles on the PHP Chinese website!