PHP ignore_user_abort 使用

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

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

Demo

用于某些免费的 php 虚拟机很不错
[代码]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;  //开启定时任务
?>

参考

PHP自动定时循环执行任务
PHP实现执行定时任务的几种思路详解
PHP 函数 ignore_user_abort定时执行任务的实现

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,997评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,612评论 25 708
  • Composer Repositories Composer源 Firegento - Magento模块Comp...
    零一间阅读 3,970评论 1 66
  • 日子依旧在一天天的过着,时光总会闪现不同的精彩,这几天的日子感觉自己还是应该恢复每天晚上去记录一天发生的点滴,这样...
    最佳姐妹阅读 244评论 2 0
  • #记梦#终于又做了一个zombie梦 在很久没做什么刺激好玩的梦,只有一些小清新短的梦以后,终于做了这个梦。 开端...
    这不是一个昵称阅读 309评论 0 1