长时间运行的PHP程序解决方案

来源:互联网 发布:java项目开发环境 编辑:程序博客网 时间:2024/05/17 04:22
描述:有时候,PHP程序会面临AJAX过来的调用,但逻辑处理的运行又比较漫长,如外部调用svncheckout某个项目,那么就会导致几个问题:客户端超时,返回数据集超大,服务器端脚本超时,内存占用巨大等

比较了几个解决方案,以下这个能比较好地解决上述问题,对服务器的调整也不会造成太大影响。
伪daemon程序,原理:主php程序执行,并不等结果完成就直接返回,中断与浏览器连接,但是断开后仍能保持执行状态,执行过程中建立log文件以备查询,相当于一个daemon。浏览器端的ajax可设时间轮询执行状态,轮询程序查询log文件并返回结果;

步骤:
1. 设置.htaccess,确保返回的Content-Type encoding不是gzip

<IfModule mod_env.c>
SetEnvIfNoCase Request_URI "\.php$" no-gzip dont-vary
</IfModule>


2.设置中断返回以及长时间运行设置
set_time_limit(0); 
ignore_user_abort
(true);    
// buffer all upcoming output - make sure we care about compression:
if(!ob_start("ob_gzhandler"))
    ob_start
();        
echo $stringToOutput
;    
// get the size of the output
$size
= ob_get_length();    
// send headers to tell the browser to close the connection    
header
("Content-Length: $size");
header
('Connection: close');    
// flush all output
ob_end_flush
();
ob_flush
();
flush
();    
// close current session
if (session_id()) session_write_close(); //close connection

// here, do what you want.
0 0
原创粉丝点击