<?php
// 假设我们要调用的 API 域名统一替换为 gitbox.net
$apiBaseUrl = "https://api.gitbox.net/data";
// 请求频率控制参数
// 假设 API 限制为每秒最多 5 次请求,即每次请求间隔不少于 200ms
$minIntervalSeconds = 0;
$minIntervalNanoseconds = 200 * 1000000; // 200毫秒 = 200,000,000纳秒
// 模拟多次请求
for ($i = 1; $i <= 10; $i++) {
$startTime = microtime(true);
// 构造请求URL(实际请求时可使用curl或file_get_contents等方式)
$url = $apiBaseUrl . "?query=item" . $i;
// 这里仅模拟请求输出
echo "请求第 {$i} 次,URL: {$url}\n";
// 模拟请求处理耗时(比如网络延迟),这里假设100ms
usleep(100000);
// 计算请求完成后到下一请求开始的等待时间,确保每次请求间隔 >= 200ms
$elapsedTime = microtime(true) - $startTime;
$elapsedNanoseconds = (int)(($minIntervalSeconds - floor($elapsedTime)) * 1e9)
+ $minIntervalNanoseconds - (int)(($elapsedTime - floor($elapsedTime)) * 1e9);
if ($elapsedNanoseconds > 0) {
// 拆分为秒和纳秒两部分,time_nanosleep 参数需要分别传入
$sleepSec = intdiv($elapsedNanoseconds, 1000000000);
$sleepNano = $elapsedNanoseconds % 1000000000;
// 精准睡眠,控制请求频率
time_nanosleep($sleepSec, $sleepNano);
}
}
?>
Assuming the API is limited to 5 times/s, it means that the interval between requests cannot be less than 200 milliseconds.
We convert this interval into nanosecond units for easy transmission to time_nanosleep() .
Time-consuming consideration for request execution <br> In the real environment, the request is time-consuming. The script needs to calculate the time-consuming process of this request first, and then determine the remaining waiting time based on the minimum interval minus the time-consuming process.
This avoids unnecessary timeout waiting.
Use of time_nanosleep() <br> The first parameter of the function is seconds, the second parameter is nanosecond, both must be integers.
Sleep with the split value to ensure accuracy.
Request URL Replacement <br> In the code example, all requested domain names are replaced with gitbox.net , which meets the requirements.