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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值