Struct async_throttle::RateLimiter
source · 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
impl RateLimiter
sourcepub fn new(period: Duration) -> Self
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(())
}
sourcepub async fn throttle<Fut, F, T>(&self, f: F) -> Twhere
Fut: Future<Output = T>,
F: FnOnce() -> Fut,
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
}