PHP定时脚本四种简单代码实现笔记!

思路大致如下:

1.设置客户端是否关闭浏览器都执行定时脚本。
2.解除PHP脚本30s时间限制
3.要执行的PHP代码。。。。。一大坨。。。。。
4.自己调用自己从头执行代码 。。。。
5.设置关闭按钮 。。。。
案例一使用 while 循环:
 
header("content-type:text/html;charset=utf8");  
  
        ignore_user_abort(true); //无论客户端是否关闭浏览器都执行代码 
        set_time_limit(0); //解除PHP脚本时间30s限制
   
 
        $close = 0; // include "config.php";//设置关闭按钮
        if (!$close){
            while(true){//死循环
                file_put_contents"test.php",time(),FILE_APPEND);
                sleep(5); 
            }
        }
 

分页循环处理
$s = 0;#起始页
$e = 100;#每页100条
while(true){#死循环
    
    file_put_contents('log.log',$s."\n",FILE_APPEND); #写入数据
    if($s ==100000){ #跳出循环
        break;
    }
    $s = $s+$e;#下一页
}
PHP定时脚本四种简单代码实现笔记!_第1张图片
image.png
案例二使用 include 重新加载文件执行:

dsjb.php文件代码如下:


header("content-type:text/html;charset=utf8");
 
ignore_user_abort(true);//无论客户端是否关闭浏览器都执行代码



set_time_limit(0);//解除PHP脚本时间30s限制

$close = 1;// include "config.php";//设置关闭按钮(放入配置文件。下次开启或关闭直接修改配置文件值)
if($close) exit();//break;die;

$time = 5;//休息时间

$url = "http://top.baidu.com/buzz?b=1";//百度热点地址

$content = file_get_contents($url);
    
    preg_match_all('/[\s\S]*<\/td>/',$content,$arr);
 
    preg_match_all('/]*>.*<\/a>/',$arr[0][0],$res);
    shuffle($res[0]);//打乱数组顺序
    
    for($i=0;$i<50;$i++){
        $tag = strip_tags($res[0][$i]);
        $str.="\r\n".$tag."\r\n";
    }
    $run = file_put_contents(time().".txt",$str);
    sleep($time);
    
    include("dsjb.php");//引入自己,继续执行代码 

案例三使用 函数自调用:
   
header("content-type:text/html;charset=utf8");  
  
ignore_user_abort(true); //无论客户端是否关闭浏览器都执行代码 
set_time_limit(0); //解除PHP脚本时间30s限制
   
 
$close = 0; // include "config.php";//设置关闭按钮
 
 
 
function test(){
    global $close;//函数内调用外部变量,使用 global 
    if(!$close){//如果没关闭 ,休息一下,继续函数自调用 
            file_put_contents("hello.txt","hello\n\r",FILE_APPEND);//执行的动作
        sleep(5);
        test();
    }
    
 }
 test();//启动定时脚本程序
  
案例四使用 meta 标签 自刷新:
  header("content-type:text/html;charset=utf8"); //设置编码
  date_default_timezone_set('Asia/Shanghai');//设置时区
  ignore_user_abort(true); //无论客户端是否关闭浏览器都执行代码 
  set_time_limit(0); //解除PHP脚本时间30s限制
   
 
    $close = 0; // include "config.php";//设置关闭按钮
  
    if(!$close){//如果没关闭则执行代码
        file_put_contents("hello.txt",date('Y-m-d H:i:s')."\n\r",FILE_APPEND);//执行的动作
        sleep(3);//休息 3 秒
      echo' '; //再休息 2 秒, 实际休息时间为 5 秒
    }
    

你可能感兴趣的:(PHP定时脚本四种简单代码实现笔记!)