Home >Backend Development >PHP Tutorial >Detailed explanation of PHP implementation of scheduled tasks
PHP should be said to be relatively weak in this regard. If you only use php to implement it, it can be implemented as follows:
<?php ignore_user_abort();//关闭浏览器后,继续执行php代码 set_time_limit(0);//程序执行时间无限制 $sleep_time = 1;//多长时间执行一次 do{ $fp = fopen('test.txt','a+'); fwrite($fp,"这是一个php博客:phpddt.com \n"); fclose($fp); sleep($sleep_time); }while(true); ?>
But when I execute the script, even if I close the browser, I cannot stop the program at all. , so you need a switch to execute the script. You can implement it by introducing an external file. During the while loop, just include the switch variable. Then it can be achieved like this:
Create an external imported variable file switch.php with the following content:
<?php return 1;//1执行脚本 0退出执行脚本 ?>
The improved script is as follows:
<?php ignore_user_abort();//关闭浏览器后,继续执行php代码 set_time_limit(0);//程序执行时间无限制 $sleep_time = 5;//多长时间执行一次 $switch = include 'switch.php'; while($switch){ $switch = include 'switch.php'; $fp = fopen('test.txt','a+'); fwrite($fp,"这是一个php博客:phpddt.com $switch \n"); fclose($fp); sleep($sleep_time); } exit(); ?>
This script is only feasible for testing, and the specific efficiency should not be high. For lamp, you are completely This can be achieved using crontab.
Add a small piece of code:
ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行. set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去 $interval=60*30;// 每隔半小时运行 do{ //这里是你要执行的代码 sleep($interval);// 等待5分钟 }while(true);
This is all about the implementation of PHP scheduled execution tasks. There will be related articles to share with you later, don’t miss it.
The above has introduced a detailed explanation of how to implement scheduled tasks in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.