PHP在发送下一个api请求之前等待

时间:2015-12-06 21:24:27

标签: php api curl cron request

我有一个网站从API中提取价格。问题是如果你在很短的时间内向这个API发送超过10个请求,你的ip会暂时被阻止(我不确定这是否只是localhost上的一个问题,或者它是否也是一个问题来自网络服务器,我假设后者。)

对API的请求返回一个JSON对象,然后我将其解析并将其中的某些部分存储到我的数据库中。数据库中大约有300个条目,因此我需要向此API提出约300个请求。

我最终会得到一个每x小时一次的cron作业,所有的价格都是从API更新的。该作业调用我所拥有的php脚本执行所有请求和数据库处理。

有没有办法让脚本在更长的时间内发送请求,而不是立即?我遇到的问题是,大约20左右的请求后,ip被阻止,接下来的50个左右请求就没有返回数据。

我查看了sleep(),但是读到它只会将结果存储在缓冲区并等待,而不是在每次请求之后等待。

以下是cron作业将调用的脚本:

define('HTTP_NOT_FOUND', false);
define('HTTP_TIMEOUT', null);

function http_query($url, $timeout=5000) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT_MS, $timeout);

    $text = curl_exec($curl);

    if($text) {
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        switch($code){
            case 200:
                return $text;
            case 404:
                return -1;
            default:
                return -1;
            }
        }
    return HTTP_TIMEOUT;
}

function getPrices($ID) {

    $t = time();
    $url = url_to_API;
    $result = http_query($url, 5000);
    if ($result == -1) { return -1; }
    else {
        return json_decode($result)->price;
    }
}

connectToDB();

$result = mysql_query("SELECT * FROM prices") or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
    $id = $row['id'];
    $updatedPrice = getItemPrices($id);
    .
    .
    echo $updatedPrice;
    . // here I am just trying to make sure I can get all ~300 prices without getting any php errors or the request failing (since the ip might be blocked)
    .
}

1 个答案:

答案 0 :(得分:0)

sleep()不应该影响/缓冲对数据库的查询。如果您需要立即打印,可以使用ob_flush()。另外,请确保使用set_time_limit()设置最长执行时间,这样脚本就不会超时。

set_time_limit(600);

while ($row = mysql_fetch_array($result)) {
  $id = $row['id'];
  $updatedPrice = getItemPrices($id);
  .
  .

  echo $updatedPrice;

  //Sleep 1 seconds, use ob_flush if necessary
  sleep(1);

  //You can also use usleep(..) to delay the script in milliseconds
}
相关问题