如何暂停此循环的固定时间?

问题描述:

我有一个数组,它将读取文本文件并执行api调用,然后将这些结果插入到mySQL中。但是当它批量运行时,来自API服务器的响应速度很慢,并且由于许多结果都是空白的。我在看的是有没有一种方法来暂停每个呼叫的循环说5秒从api服务器获得结果,所以它不会得到空白的结果。如何暂停此循环的固定时间?

这个代码如下

//connect to your database 
mysql_connect("localhost", "root", "password"); 
mysql_select_db("somedb"); 

//read your text file into an array, one entry per line 
$lines = file('filename.txt'); 

//loop through each website URL 
foreach ($lines as $website_url) { 

    //make the request to the compete API 
    $response = file_get_contents("http://apps.compete.com/sites/" . $website_url . "/trended/rank/?apikey=0sdf456sdf12sdf1"); 

    //decode the request 
    $response = json_decode($request); 

    //get the rank from the response 
    $rank = $response['something']; 

    //insert the website URL and its rank 
    mysql_query("INSERT INTO website_ranks (website_url, rank) VALUES ('" . mysql_real_escape_string($website_Url) . "', " . $rank . ")"); 

} 
+1

`睡眠(5)`不会做呢? – ircmaxell 2010-12-22 20:39:04

使用睡眠命令

sleep (5); 

那岂不是更有意义的验证服务器响应,而不是睡的时间任意金额是多少?

我建议使用一种替代方法,而不是使用单个INSERT语句循环,而是在您的RDBMS提供程序中使用BULK INSERT语法。这将大大加快这一进程。

这句法通常是这样的:

INSERT INTO表名(COL1,COL2)VALUES(...)