Struct lib_wc::sync::RateLimiter
source · pub struct RateLimiter { /* private fields */ }
Expand description
RateLimiter
is a tool which can control the rate at which processing happens.
Examples
use std::time::{Duration, Instant};
use lib_wc::sync::RateLimiter;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
static PERIOD: Duration = Duration::from_millis(10);
static COUNT: AtomicUsize = AtomicUsize::new(0);
async fn do_work() { COUNT.fetch_add(1, SeqCst); }
#[tokio::main]
async fn main() {
let rate_limiter = RateLimiter::new(PERIOD);
let start = Instant::now();
for _ in 0..10 {
rate_limiter.throttle(|| do_work()).await;
}
// The first call to throttle should have returned immediately, but the remaining
// calls should have waited for the interval to tick.
assert!(start.elapsed().as_millis() > 89);
// All 10 calls to do_work should be finished.
assert_eq!(COUNT.load(SeqCst), 10);
}
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 lib_wc::sync::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 lib_wc::sync::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
}