PHP关闭连接并在后台继续执行



我想在关闭连接后继续执行脚本。

这是我试过的。。

log_message('debug','Test started' );
//Show all errors   
error_reporting(E_ALL); 
//Configurations 
@ini_set("output_buffering", "Off");
//@ini_set('implicit_flush', 1);
@ini_set('zlib.output_compression', 0);
//User abort & maximum time
ignore_user_abort(true);
set_time_limit(0);
//check the level       
if (ob_get_level() == 0) {
    ob_start();
}
//Actual output
echo('hello world ...'); 
// get buffer length        
$size = ob_get_length(); 
// set content length
header("Content-Length:$size"); 
//close the connection 
header("Connection:close");  
// content encoding 
header("Content-Encoding: none"); 
//content type
header("Content-Type: text/html; charset=utf-8"); 
//Release buffer
ob_flush();
ob_end_flush();  
flush(); 
// Continue on background
// never gonna execute from here ...
sleep(20); 
//There is no aliens (class) exists , expecting error on log
$alien = new alienEncoder(); 
$alien->get_aliens( new alienDecoder() );
log_message('debug','End Test'); 

执行CONTINUE部分时一切正常(在FLUSH之后停止),服务器上没有错误日志。

相同的代码在另一个主机中可以工作,但在这里不行。

请帮忙。

SERVER:IIS 7.5共享,使用Codeigniter

备注

  1. 没有alienEncoder()或类似的东西,所以我是期望服务器上有一些错误日志,但没有错误
  2. ResponceBufferLimit设置为零
  3. 使用CGI/FastCgi

PHP-FPM有一个专门用于此目的的功能,fastcgi_finish_request()

尽管我不知道如何使用IIS 运行它

Php与apache请求系统耦合。它在收到请求时启动完成后,请求将关闭。

Flush只向客户端发送部分响应,但不会终止此响应,因此浏览器仍将挂起,等待更多内容。它将消耗带宽、apache和php资源。此外,我不得不说这是一个相当糟糕的做法。

在不降低客户端速度的情况下执行计算密集型任务的最佳方法是使用延迟任务系统。我个人推荐resque(谷歌一下!)。它使您能够将操作添加到队列中,然后工作人员将处理所有排队的任务并计算它们。

对于一个运行在云主机上且几乎免费的选项,请查看ironmq(来自iron.io)。它们的工作方式相同(您向队列添加一个任务,然后队列调用一个可配置的url,该url将触发任务计算)

最新更新