最近我遇到了类似的问题。发出 Ajax 请求将有 2 个问题。第一个,导航器将被冻结。第二个,大多数服务器会在运行脚本一段时间后引发错误(在某些情况下,通常可以引发 30 秒)。
我第一次处理它的方式是在文件中记录相关数据并将进程划分为较小的进程,并且在每次成功的 ajax 响应时,重新启动下一步直到任务结束,将完成百分比保存到会话变量在每个请求上,以及恢复它的流程的当前步骤,就像这样:
function stepOnTask(){
ajax.post("file.php", "action:doPartialTask", function(response){
if ( response.taskFinished ) alert("Task Done");
else{
showProgress(response.currentProgress);
stepOnTask();
}});
}
但这对我的桌面导航器来说真的很紧张,而且它经常崩溃,并不是说你不能同时什么都不做,所以我完全改变了它到另一种方法,在 php 中使用后台进程并保存相关信息(估计时间、开始时间等...)在由已启动进程的 pid 命名的文件中,并每隔 x 秒向该文件发出一次请求以检查并显示进度。
最后一点有点长,如果您不要求我,我不会发布代码,因为我不确定您正在寻找的那种解决方案。
祝你好运。
编辑
PHP 后台进程样式
Class BackgroundScript{
public $win_path = "C:\\xampp\\htdocs\\www\\yourProject";
public $unix_path = "/home/yourFolder/yourProject.com";
public $script = NULL;
public $command = NULL;
public $pid = NULL;
public $start_time = NULL;
public $estimated_time = NULL;
public $ellapsed_time = NULL;
public $status_file = NULL;
public function __construct($script = ""){
$this->script = $script;
if ( self::get_os() == "windows" ){
$this->command = "start /b C:\\xampp\\php\\php.exe ".$this->win_path."\\".$this->script;
}else{
$this->command = "php ".$this->unix_path."/".$this->script;
}
}
public static function conPID($pid){
if ( file_exists(dirname(__FILE__)."/pids/".$pid.".json") ){
$bgScript = new BackgroundScript();
$process_info = json_decode(file_get_contents(dirname(__FILE__)."/pids/".$pid.".json"));
foreach ( $process_info as $key=>$val ){
$bgScript->$key = $val;
}
return $bgScript;
}else {
return false;
}
}
public static function get_os(){
if ( substr(php_uname(), 0, 7) == "Windows" ) return "windows";
else return "unix";
}
public function saveToFile(){
$path_to_pfolder = self::get_os()=="windows"? $this->win_path."\\pids":$this->unix_path."/pids";
if ( !( file_exists($path_to_pfolder) && is_dir($path_to_pfolder)) ){
mkdir($path_to_pfolder);
}
$fileHandler = fopen($path_to_pfolder."/".$this->pid.".json", "w");
$this->status_file = $path_to_pfolder."/".$this->pid.".json";
fwrite($fileHandler, json_encode($this));
fclose($fileHandler);
return $this->status_file;
}
public function removeFile(){
$path_to_pfolder = self::get_os()=="windows"? $this->win_path."\\pids":$this->unix_path."/pids";
unlink($path_to_pfolder."/".$this->pid.".json");
}
public function run($outputFile = '/dev/null'){
if ( self::get_os() == "windows" ){
$desc = array(
0 => array("pipe", "r"), // stdin es una tubería usada por el hijo para lectura
1 => array("pipe", "w"), // stdout es una tubería usada por el hijo para escritura
);
//proc_get_status devuelve el pid del proceso que lanza al proceso, o sea, del padre, y hay que hacer algo más para obtener el pid real del proceso que genera el archivo
$p = proc_open($this->command, $desc, $pipes);
$status = proc_get_status($p);
$ppid = $status["pid"];
//Ya tenemos el pid del padre, ahora buscamos el del último proceso hijo, que será el que acabamos de lanzar, y lo guardamos
$output = array_filter(explode(" ", shell_exec("wmic process get parentprocessid,processid | find \"$ppid\"")));
array_pop($output);
$this->pid = end($output);
//Cerramos el proceso padre, esto es lo que hará que no se nos quede pillada la aplicación mientras el "servidor" trabaja.
proc_close($p);
} else{
//En unix e ma facilico
$this->pid = trim(shell_exec(sprintf('%s > %s 2>&1 & echo $!', $this->command, $outputFile)));
}
$this->ellapsed_time = 0;
$this->start_time = date("Y-m-d H:i:s");
return $this->saveToFile();
}
public function isRunning()
{
try {
$result = shell_exec(sprintf('ps %d', $this->pid));
if(count(preg_split("/\n/", $result)) > 2) {
return true;
}
} catch(Exception $e) {}
return false;
}
public function kill(){
$this->removeFile();
if ( self::get_os() == "windows" ){
shell_exec(" taskkill /PID ".$this->pid);
} else{
// shell_exec(sprintf('kill %d 2>&1', $this->pid));
shell_exec(sprintf('kill '.$this->pid));
}
}
public function getPid(){
return $this->pid;
}
public static function getAll(){
$path_to_pfolder = self::get_os()=="windows"? self::$win_path."\\pids":self::$unix_path."/pids";
if ( !( file_exists($path_to_pfolder) && is_dir($path_to_pfolder)) ){
return array();
}
$archivos = scandir($path_to_pfolder);
$processes = array();
foreach ($archivos as $archivo){
if ( is_file($path_to_pfolder."/".$archivo) ){
$json = file_get_contents($path_to_pfolder."/".$archivo);
$info = json_decode($json);
$process = new BackgroundScript();
foreach ( $info as $key=>$val ){
$process->$key = $val;
}
$processes[] = $process;
}
}
return $processes;
}
public function view(){
$segundos_estimados = $this->estimated_time;
$segundos_transcurridos = time() - strtotime($this->start_time);
$segundos_restantes = max($segundos_estimados - $segundos_transcurridos, 0);
/*
$minutos_estimados = floor($segundos_estimados/60);
$segundos_estimados = $segundos_estimados - $minutos_estimados*60;
$minutos_restantes = floor($segundos_restantes/60);
$segundos_restantes = $segundos_restantes - $minutos_restantes*60;
*/
$estimado = date("i:s", strtotime("1983-09-23 00:00:00")+$segundos_estimados);
$restante = date("i:s", strtotime("1983-09-23 00:00:00")+$segundos_restantes);
if (!$segundos_estimados){
$html="<a>".$this->nombre_diario."
<!--<br>Tiempo Estimado: <span class='estimado'>Calculando</span>-->
<br>Tiempo Restante: <span class='restante' data-time='".$segundos_restantes."'>Calculando</span></a>";
}elseif (!$segundos_transcurridos){
$html="<a>".$this->nombre_diario."
<!--<br>Tiempo Estimado: <span class='estimado'>Guardando</span>-->
<br>Tiempo Restante: <span class='restante' data-time='".$segundos_restantes."'>Guardando</span></a>";
}else{
$html="<a>".$this->nombre_diario."
<!--<br>Tiempo Estimado: <span class='estimado'>".$estimado."</span>-->
<br>Tiempo Restante: <span class='restante' data-time='".$segundos_restantes."'>".$restante."</span></a>";
}
return $html;
}
}
好的,我知道代码可能看起来有点糟糕,但它可以工作。
现在,我将向您展示我的使用方式,您必须根据自己的风格调整它。
我有一个名为 controller.php 的文件,它处理我的项目中的所有操作,看起来很像这样:
if (isset($_POST) && isset($_POST["action"]) ) $action= $_POST["action"];
else $action= $argv[1];
switch ($action) {
case "performTask1":{
task1();
}
break;
case "performTask2":{
task2();
}
break;
case "performTask2inBackground":
{
$process = new BackgroundScript("controller.php performTask2");
$response["file_with_info"] = $process->run();
}
break;
echo json_encode($response);
}
仅此而已。
当然,在课程开始时您必须更改 win_path 和 unix_path 以匹配您自己的机器路径到项目。我同时使用它们,所以我的本地测试环境和真实服务器版本工作相同。还没有 mac 版本:P(希望你不需要它)。
另外需要注意的是,如果您的 php 文件夹位于不同的路径中,您可能必须在构造函数中更改构建变量“command”的路径。
将在项目的根目录创建一个名为“pid”的目录,以保存包含信息的文件,名称为 {pid_of_the_process}.json。请注意,在您的过程中,您可以在此文件中填写有用的信息,否则,它将没有有用的信息。
执行此操作的正确方法是,在您的脚本中执行以下操作:
...
do{
doLotsOfThings();
$bgScript= BackgroundScript::conPID(getmypid());
$bgScript->estimated_time = recalculate_estimated_time();
$bgScript->ellapsed_time = recalculate_remaining_time();
$bgScript->saveToFile();
} while($whatever)
//END
$process->kill();
要在任何时候出于任何目的检索有关正在运行的进程的信息,您可以使用BackgroundScript::getAll();,以显示进程的估计剩余时间的快照,例如,这就是为什么留下“视图”方法的原因,这可能对你没有用,但我用它来检索状态并按需向用户显示剩余时间。
出于调试目的,我建议您找到非常需要的 php 错误日志文件,因为您不会有直接的浏览器反馈,请记住,您可以简单地将生成的命令粘贴到控制台并运行该过程,如果您想要了解正在发生的事情的第一手信息。
最后,我想感谢@FlorianEckerstorfer,他的后台进程库帮助我开发了我在此处发布的解决方案。