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

后端开发   发布日期:2023年05月14日   浏览次数:243

我们通常做定时任务需要做到代码自动执行,往往会借助系统来实现,例如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可以,但是弊端多。还是用计划任务定时访问比较好。

以上就是PHP使用ignore_user_abort()实现定时循环执行PHP任务的方法的详细内容,更多关于PHP使用ignore_user_abort()实现定时循环执行PHP任务的方法的资料请关注九品源码其它相关文章!