详解PHP实现执行定时任务_PHP

WBOY
Release: 2016-05-29 11:47:19
Original
949 people have browsed it

PHP在这方面应该说是比较弱,如果只用php去实现可以如下:

<?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);
 
?>

Copy after login

但是当我执行脚本的时候,即使我关闭了浏览器,我根本就没法去停止这段程序了,所以你需要一个执行脚本的开关,你可以用外部文件引入的方法来实现,在while循环的时候,include开关变量即可。那么就可以这样实现:
建立外部引入变量文件 switch.php 内容如下:

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

改良脚本如下:

<?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();
 
?>

Copy after login

这个脚本只是测试可行,具体效率应该不高,对于lamp,你完全可以使用crontab 来实现。
再补充一段小代码:

ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行.
set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去
$interval=60*30;// 每隔半小时运行
do{
  //这里是你要执行的代码  
  sleep($interval);// 等待5分钟
}while(true);
Copy after login

关于PHP定时执行任务的实现就为大家介绍这么多,之后还有相关文章为大家分享,不要错过。

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!