
Limit how often an asynchronous function can be called
Source:R/async_rate_limit.R
async_rate_limit.RdAsynchronous version of rate_limit(). It allows at most calls calls to
start in any window of period seconds, but a call over the limit is
scheduled with later::later() instead of sleeping, so the session carries
on. The decorated function returns a promise that
follows the wrapped function's result, a plain value or a promise.
Details
Each call reserves its slot when it is made, so calls start in order and
queued calls count toward the limit. As with rate_limit(), an error still
uses its slot. It limits when calls start, not how many run, so slow calls can
overlap. Stack it inside async_retry() to throttle every attempt.
Needs the promises and later packages, and an event loop.
Examples
if (FALSE) { # \dontrun{
f := async_rate_limit(calls = 2, period = 0.2) %@% function(i) i
start <- Sys.time()
for (i in 1:4) {
local({
i <- i
promises::then(f(i), function(value) {
cat("call", value, "at", round(as.numeric(Sys.time() - start), 1), "s\n")
})
})
}
while (!later::loop_empty()) later::run_now(0.05)
} # }