Detailed explanation of PHP implementation of scheduled tasks

WBOY
Release: 2016-07-29 09:09:30
Original
1103 people have browsed it

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:

<&#63;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);
 
&#63;>

Copy after login

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:

<&#63;php
return 1;//1执行脚本 0退出执行脚本
&#63;>
Copy after login

The improved script is as follows:

<&#63;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();
 
&#63;>

Copy after login

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);
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!