Class
RateLimiter
Lets events pass at a fixed rate, shared by every coroutine that calls wait().
Introduction#
The constructor starts a coroutine in the current frame that issues one permit every 1 / $eventsPerSecond seconds, and it stops when the limiter is dropped. The first wait() returns at once. A $burst above 0 lets permits accumulate while nobody waits: after an idle period, up to $burst + 1 events pass at once. A limiter is a SelectableInterface: it is ready when a permit is available.
Class synopsis#
final class RateLimiter implements SelectableInterface {
/* Methods */
public RateLimiter::__construct(float $eventsPerSecond, int $burst = 0)
public RateLimiter::await(float $timeout = PHP_FLOAT_MAX): void
public RateLimiter::isReady(): bool
public RateLimiter::wait(): void
}Methods#
| Method | Description |
|---|---|
__construct | Creates the limiter and starts its coroutine. |
await | Waits for a permit and takes it. |
isReady | Returns true if a permit is available. |
wait | Waits for a permit, which delays the coroutine as much as the rate requires. |
Examples#
phasync::run(function () {
$limiter = new phasync\Util\RateLimiter(10);
for ($i = 0; $i < 5; $i++) {
$limiter->wait();
echo "at most 10 per second\n";
}
});See also#
SelectableInterfaceAn object that can be asked whether using it would block, and waited for until it would not.phasync::sleepPauses the current coroutine for$seconds, and lets the others run meanwhile.
Used in#
- Connections, pools and limitsA worker needs few database connections. Borrow one for a query or a transaction and give it back.