pub struct RateLimiter { /* private fields */ }
Expand description

RateLimiter is a tool which can control the rate at which processing happens.

Examples

use async_throttle::RateLimiter;

#[tokio::main]
async fn main() {
   let period = std::time::Duration::from_millis(10);
   let rate_limiter = RateLimiter::new(period);
    
   // Takes 90ms to complete, the first iteration is instant, the next 9 iterations take 100ms
   for _ in 0..10 {
      rate_limiter.throttle(|| async { /* work */ }).await;
   }
}

Implementations§

source§

impl RateLimiter

source

pub fn new(period: Duration) -> Self

Creates a new rate limiter.

Examples
use tokio::sync::Mutex;
use anyhow::Result;
use std::time::Duration;
use async_throttle::RateLimiter;

#[tokio::main]
async fn main() -> Result<()> {
    RateLimiter::new(Duration::from_millis(10));
    Ok(())
}
source

pub async fn throttle<Fut, F, T>(&self, f: F) -> Twhere Fut: Future<Output = T>, F: FnOnce() -> Fut,

Throttles the execution of a function.

Examples
use async_throttle::RateLimiter;
use anyhow::Result;
use std::sync::Arc;

async fn do_work() { /* some computation */ }

async fn do_throttle(limiter: Arc<RateLimiter>) {
   limiter.throttle(|| do_work()).await
}

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V