php 循环爬虫 or 持久执行任务 总断掉服务 解决,flush(),ob_flush()的组合使用

<?php

namespace app\controller;

header('Content-type:text/html;charset=utf8');

use app\BaseController;
use think\App;
use think\facade\Db;

/**
 * 测试php不间断循环
 * Class organizational
 * @package app\controller
 */
class Fresh extends BaseController
{

   public function index()
   {
       if (ob_get_level() == 0) ob_start();
       set_time_limit(0);
       ini_set('memory_limit', '1G');
       ini_set('default_socket_timeout', -1);
       $waitadd = Db::connect('os')->table('bankdata_temp')->select();

       //为了方便测试,这里逐单条添加入表
       foreach ($waitadd as $k => $v) {
           flush(); //ob_flush()一定要组合使用 ,否则不起作用
           ob_flush();
           $recorddata = array();
           $recorddata['aaa'] = $v['aaa'];
           $recorddata['bbb'] = $v['bbb'];

           Db::connect('test')
               ->table('test_table')
               ->insertGetId($recorddata);
           echo ($k+1)."\r\n";  //必须要在循环中 打印哦 ,不然flush就不起作用了
           //当前apache通过浏览器访问
           if (strpos(strtolower($_SERVER['SERVER_SOFTWARE']), 'apache') !== false) {
               echo str_pad('',4096)."\n";
           }
           sleep(1); //停留一秒观看浏览器 弹出信息
       }
       ob_end_flush();
       exit('ok');
   }


}

  

posted @ 2021-10-14 21:55  撑一支船蒿  阅读(81)  评论(0编辑  收藏  举报