2011-08-19 66 views
4

我正在使用web服务发送100个http帖子。但是,该服务只允许每秒5个。我想知道usleep命令是否是最好的方法。例如:使用usleep()的节流阀cURL

foreach($JSONarray['DATABASE'] as $E) 
{ 
    $aws = curl_init(); 
    //curl stuff 
    curl_exec($aws); 
    curl_close($aws); 
    usleep(200000); 
} 
+1

应该没问题,虽然这会稍微偏离一点,因为请求本身需要一定的时间。如果你想最大限度地提高效率,你应该考虑每个请求花了多长时间,并将其从20000毫秒的暂停中拿走。 –

+0

如何使用['curl_multi'](http://php.net/curl_multi_init),您可以控制它以保持最多5个同时运行或在任何给定时间启动? – salathe

回答

2

现在,这是未经测试,但它应该为你提供什么,我会做的想法(也许这只是片段工作,因为它是 - 谁知道...):

// presets 
$thissecond = time(); 
$cnt = 0; 

foreach($JSONarray['DATABASE'] as $E) 
{ 
    while ($thissecond == time() && $cnt > 4) { // go into "waiting" when we going to fast 
    usleep(100000); // wait .1 second and ask again 
    } 

    if ($thissecond != time()) { // remember to reset this second and the cnt 
    $thissecond = time(); 
    $cnt = 0; 
    } 

    // off with the payload 
    $aws = curl_init(); 
    //curl stuf 
    curl_exec($aws); 
    curl_close($aws); 

    // remember to count it all 
    $cnt++; 
}