欢迎您来到,李雷博客 | PHP博客        登录  |  注册

PHP使用ignore_user_abort()实现定时循环执行PHP任务的方法

更新:2020-03-29 09:06:14
人气:1742
来源:本站整理
A+

我们通常做定时任务需要做到代码自动执行,往往会借助系统来实现,例如linux的crontab或者windows的定时计划等等,现在分享一个纯代码实现的自动执行。

下面是用到的一窜PHP的执行代码,效率不是很好,但是能保持任务自动执行。

结合set_time_limit()函数实现一个循环脚本执行任务

<?php
ignore_user_abort();// 即使client 断开(如关闭浏览器),PHP 脚本也可以继续执行。
set_time_limit(0);
$interval=60*15;
do{
  if(xxx)break;//记住退出
  //执行的业务}while(true);
  ?>
  //说明:每隔15分钟循环执行

自定义实现文件输出并跟踪ignore_user_abort()函数的执行结果

<?php 
ignore_user_abort ( TRUE );
set_time_limit ( 0 );
$interval = 10;
$stop = 1;
do {    
if( $stop == 10 ) break;    //退出
file_put_contents('liuhui.php',' Current Time: '.time().' Stop: '.$stop);//记得权限
$stop++;  
sleep ( $interval );
} while( true);
?>

[代码]task.php(任务主文件)

<?php
ignore_user_abort(); //关掉浏览器,PHP脚本也可以继续执行.
set_time_limit(0); // 通过set_time_limit(0)可以让程序无限制的执行下去
$interval = 15; // 每隔*秒运行
$temp_key = 0;
do {
    $time = time();
    require 'config.php';
    $mem = new Memcache();
    $mem->connect($Memcache_server, $Memcache_port);
    if ($is_send) {
        $get_time = $mem->get('tem_data');
    } else {
        $get_time = $time + 86400;
        exit();
    }
    if ($get_time == $time) {
        $mem->close();
        exit();
    } else if ($get_time > $time - $interval) {
        $mem->close();
    } else if ($temp_key == 0) {
        $temp_key = 1;
        @file_get_contents('http://******/*****.php');
        $mem->set('tem_data', $time, MEMCACHE_COMPRESSED, $Memcache_date);
        $mem->close();
        sleep(mt_rand(1, 3));
        $temp_key = 0;
    }else{
        $mem->close();
        exit();
    }
    //这里是你要执行的代码
    sleep($interval); // 等待*秒钟
} while (true);
?>

[代码]config.php(配置文件)

<?php
$Memcache_server = '127.0.0.1';
$Memcache_port = 11211;
$Memcache_date = 86400;
//return $is_send = false; //关闭定时任务
return $is_send = true;  //开启定时任务
?>

注:sleep可以,但是弊端多。还是用计划任务定时访问比较好。

推荐的文章
# 发表我的评论
  /     /  
# 最近评论
暂时还没有评论,要不要说点什么?
  Ads by Google
  联系博主
Hello,本博客系统采用PHP和MySql开发,程序开发完全是因为个人爱好,是自己纯手写PHP源代码,未采用任何PHP框架!
QQ:858353007   微信号:lileihot123
网站地图
会员服务
关于我们
QQ:858353007
 
广告服务
加我微信
移动端访问
 
 
Copyright © 2014- 2024 www.mdaima.com All Rights Reserved.
李雷博客,专注PHP经验、PHP教程及PHP源代码开源下载分享的PHP博客!   ICP备案号:京ICP备10202169号-4