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 can’t stop the program at all, so you need a switch to execute the script, which you can do 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 can use crontab to implement it.
Add a little 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, so don’t miss it.