Struct mysteriouspants_throttle::Throttle [−][src]
pub struct Throttle<TArg> { /* fields omitted */ }
Methods
impl<TArg> Throttle<TArg>
[src]
impl<TArg> Throttle<TArg>
pub fn new_variable_throttle<TDelayCalculator: Fn(TArg, Duration) -> Duration + 'static>(
delay_calculator: TDelayCalculator
) -> Throttle<TArg>
[src]
pub fn new_variable_throttle<TDelayCalculator: Fn(TArg, Duration) -> Duration + 'static>(
delay_calculator: TDelayCalculator
) -> Throttle<TArg>
Creates a new Throttle
with a variable delay controlled by a closure. delay_calculator
itself is an interesting type, any closure which satisfies Fn(TArg, Duration) -> Duration
.
This lambda is called to determine the duration between iterations of your code - the
Duration
it returns does not signify the additional time to be waited, but the total time
that ought to have elapsed, and the difference of the times will be waited. TArg
is an
argument passsed in from a call to acquire
, so you may pass any state you may require into
the lambda to make decisions about the wait time. The Duration
argument the time that has
already elapsed from the previous call to acquire
and now. If the Duration
you return is
less than the Duration
passed to you, or is zero, that means that no additional time ought
to be waited.
An example use of a variable-rate throttle might be to wait different periods of time depending on whether your program is in backpressure, so "ease up" on your downstream call rate, so to speak.
let throttle = Throttle::new_variable_throttle( |in_backpressure: bool, time_since_previous_acquire: Duration| match in_backpressure { true => Duration::from_millis(2100), false => Duration::from_millis(1100) }); // the first one is free! throttle.acquire(false); let start_nopressure = Instant::now(); throttle.acquire(false); assert_eq!(start_nopressure.elapsed().as_secs() == 1, true); let start_yespressure = Instant::now(); throttle.acquire(true); assert_eq!(start_yespressure.elapsed().as_secs() == 2, true);
pub fn new_tps_throttle(tps: f32) -> Throttle<TArg>
[src]
pub fn new_tps_throttle(tps: f32) -> Throttle<TArg>
Creates a new Throttle
with a constant delay of tps
-1 · 1000ms, or
tps
-transactions per second.
let throttle = Throttle::new_tps_throttle(0.9); // the first one is free! throttle.acquire(()); let start = Instant::now(); throttle.acquire(()); assert_eq!(start.elapsed().as_secs() == 1, true);
pub fn acquire(&self, arg: TArg)
[src]
pub fn acquire(&self, arg: TArg)
Acquires the throttle, waiting (sleeping the current thread) until enough time has passed
for the running code to be at or slower than the throttle allows. The first call to
acquire
will never wait because there has been an undefined or arguably infinite amount
of time from the previous time acquire was called. The argument arg
is passed to the
closure governing the wait time.