Throttler

class Throttler(val window: Duration, timeSource: TimeSource.WithComparableMarks = TimeSource.Monotonic)

Runs at most one block per time window, rejecting calls that arrive too soon.

A call outside the window runs its block and returns the value; a call inside the window returns null without running anything. The window starts when a permitted block begins, and a failed or cancelled block still consumes it. Time is measured with the injected TimeSource, which makes the class testable with a virtual clock.

Thread safety: this class is safe for concurrent use from multiple coroutines and threads. run serializes its admission check with a Mutex; reset and isThrottled read or write a single volatile field, so a reset racing an in-progress run may be superseded by that run's new window.

Parameters

window

the minimum time between the starts of two permitted runs.

timeSource

the clock used to measure the window.

Throws

Constructors

Link copied to clipboard
constructor(window: Duration, timeSource: TimeSource.WithComparableMarks = TimeSource.Monotonic)

Properties

Link copied to clipboard

Returns true while a previous run's window is still open.

Link copied to clipboard

Functions

Link copied to clipboard
fun reset()

Closes the current window so the next run call is permitted.

Link copied to clipboard
suspend fun <T> run(block: suspend () -> T): T?

Runs block and returns its value, or returns null without running it while the window is open.