Three ways of implementing PHP scheduled execution
Detailed implementation
1. Windows scheduled tasks
PHP rarely runs on win servers, and the specific implementation will not be studied in detail. The principle of online implementation is probably to write a bat script, and then let the window task add and execute the bat script.
2. Linux script implementation
The crontab command is mainly used here,
How to use:
Copy code The code is as follows: crontab filecrontab [ -u user ] [ -u user ] { -l | -r | -e }
Description:
crontab is used to allow users to execute programs at a fixed time or fixed interval
Use crontab to write a shell script, and then let PHP call the shell. This is using the characteristics of Linux and should not be considered the characteristics of PHP's own language
3. PHP implements scheduled execution of planned tasks
Using php to refresh the browser requires solving several problems
PHP script execution time limit, the default is 30m Solution: set_time_limit(); or modify PHP.ini to set max_execution_time time (not recommended)
If the client browser is closed, the program may be forced to terminate. The solution: ignore_user_abort will still execute normally even if the page is closed
If the program is executed all the time, it is likely to consume a lot of resources. The solution is to use sleep to sleep the program for a while, and then execute it
Code for PHP scheduled execution:
<?php ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行. set_time_limit(3000);// 通过set_time_limit(0)可以让程序无限制的执行下去 $interval=5;// 每隔5s运行 //方法1--死循环 do{ echo '测试'.time().'<br/>'; sleep($interval);// 等待5s }while(true); //方法2---sleep 定时执行 require_once './curlClass.php';//引入文件 $curl = new httpCurl();//实例化 $stime = $curl->getmicrotime(); for($i=0;$i<=10;$i++){ echo '测试'.time().'<br/>'; sleep($interval);// 等待5s } ob_flush(); flush(); $etime = $curl->getmicrotime(); echo '<hr>'; echo round(($etime-stime),4);//程序执行时间
During testing, I found that this efficiency is not very high.
Summary:
Personally, I feel that the efficiency of PHP's scheduled task execution is not very high. It is recommended that the work of scheduled task execution be left to the shell.
The above are the three methods of executing tasks regularly in PHP. The crontab command mentioned at the end of the previous article is also briefly introduced. I hope you can gain something.