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

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

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

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

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

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

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

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

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

  1. <?php
  2. ignore_user_abort(); //关掉浏览器,PHP脚本也可以继续执行.
  3. set_time_limit(0); // 通过set_time_limit(0)可以让程序无限制的执行下去
  4. $interval = 15; // 每隔*秒运行
  5. $temp_key = 0;
  6. do {
  7. $time = time();
  8. require 'config.php';
  9. $mem = new Memcache();
  10. $mem->connect($Memcache_server, $Memcache_port);
  11. if ($is_send) {
  12. $get_time = $mem->get('tem_data');
  13. } else {
  14. $get_time = $time + 86400;
  15. exit();
  16. }
  17. if ($get_time == $time) {
  18. $mem->close();
  19. exit();
  20. } else if ($get_time > $time - $interval) {
  21. $mem->close();
  22. } else if ($temp_key == 0) {
  23. $temp_key = 1;
  24. @file_get_contents('http://******/*****.php');
  25. $mem->set('tem_data', $time, MEMCACHE_COMPRESSED, $Memcache_date);
  26. $mem->close();
  27. sleep(mt_rand(1, 3));
  28. $temp_key = 0;
  29. }else{
  30. $mem->close();
  31. exit();
  32. }
  33. //这里是你要执行的代码
  34. sleep($interval); // 等待*秒钟
  35. } while (true);
  36. ?>

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

  1. <?php
  2. $Memcache_server = '127.0.0.1';
  3. $Memcache_port = 11211;
  4. $Memcache_date = 86400;
  5. //return $is_send = false; //关闭定时任务
  6. return $is_send = true; //开启定时任务
  7. ?>

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

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