visit
Recently I encountered an issue where a CRON task contained a loop. It would make many requests to a third-party API endpoint. Within the documentation of this API, like many others, was a rate limit of 2 requests per second.
Previous we had a solution that looked something like this, which I have seen in a lot of other places:foreach($productVariants as $variant) {
sleep(2); // avoid rate limit
sendRequestToAPI($variant->id);
}
$timeBetweenEachRequest = 2;
foreach($productVariants as $variant) {
if (isset($timeStart)) {
$elapsedTime = microtime(true) - $timeStart;
$remainingTime = $timeBetweenEachRequest - $elapsedTime;
sleep($remainingTime * 1000000); // Convert seconds to microseconds
}
$timeStart = microtime(true);
sendRequestToAPI($variant->id);
}
The lead image for this article was generated by HackerNoon's AI Image Generator via the prompt "software development".