2011-08-19 19 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++; 
}