curl_multi_exec - 完成后停止所有呼叫

时间:2012-12-17 16:33:15

标签: php curl-multi

当一个成功完成时,是否可以取消curl_multi中所有正在运行的调用?似乎curl_multi在完成脚本之前等待所有进程完成,但这可能是我自己的看法。我正在尝试使用许多打开的连接调用单个URL。 URL将尽快处理请求,当第一个返回时,我想关闭剩余的连接并继续调用其余的连接。

$outArr = array();
$master = curl_multi_init();
$curl_arr = array();

$url = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on') ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$std_options = array(CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 5);

for ($i = 0; $i < 30; $i++) {
    //set custom URL so we can see which one completed.
    $std_options[CURLOPT_URL] = $url.'/sub_proc.php?somearg='.$somearg.'&tlimit='.$tlimit.'&i='.$i;

    $ch = curl_init();
    curl_setopt_array($ch,$std_options);
    curl_multi_add_handle($master, $ch);
}

do {
    while(($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
    if($execrun != CURLM_OK)
        break;
    // a request was just completed -- find out which one
    while($done = curl_multi_info_read($master)) {
        $info = curl_getinfo($done['handle']);
        if ($info['http_code'] == 200)  {
            $output = curl_multi_getcontent($done['handle']);

            // request successful.  process output using the callback function.
            $out = json_decode($output);
            $outArr = $out['board'];
        $running = false;
        break;
        //I want the code above to break all processing requests and 
        //continue with the script outside of this loop.
        } else {
            // request failed.  add error handling.
        }
    }
} while ($running);
curl_multi_close($master);

//does not execute until all requests are complete,
//causing timeouts when one failed request takes > 30 seconds
print_r($outArr);

0 个答案:

没有答案