phasync
Coordination and limits / RateLimiter

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#

MethodDescription
__constructCreates the limiter and starts its coroutine.
awaitWaits for a permit and takes it.
isReadyReturns true if a permit is available.
waitWaits for a permit, which delays the coroutine as much as the rate requires.

Examples#

Example 1
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#