在不丢失会话的情况下通过 Web 客户端触发后台任务

triggering a background task by web client without loosing session

我有一个 Web 应用程序,它应该 运行 需要时间才能完成的资源密集型任务(功能)。我通过调用 url;

来触发此任务
http://app.domain.com/process_file/@fileid

但是,正如预期的那样,Web 客户端等待任务(函数)完成。这很可能会导致超时。

请建议我可以触发任务并让用户继续浏览 webapp 的方法。

到目前为止我已经尝试了以下方法;

1. JQuery/ajax
2. Redirecting to a _blank page 

注意:我无权访问 crontab 或调度程序。我正在使用 PHP、JavaScript & fat-free 框架

尝试通过 curl 调用页面,例如:


$curl = curl_init();                
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_POST, FALSE);
curl_setopt($curl, CURLOPT_TIMEOUT, 1); 
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl,  CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_FORBID_REUSE, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($curl, CURLOPT_DNS_CACHE_TIMEOUT, 10); 
curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
curl_exec($curl);   
curl_close($curl);  

调用 url 并立即超时。

然后在您昂贵的脚本中:

header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
header("Content-Length: 1");
ignore_user_abort(true);
//your code

我相信您正在寻找 abort 函数:

function (Base $f3) {
  // process request and send response to client (could be a redirect status)
  $f3->abort(); // disconnect the client
  // perform consuming task here
}

这基本上是 Pavel Třupek 建议的解决方案,为方便起见包裹在一个方法中。