2 releases
0.1.1 | Jul 25, 2024 |
---|---|
0.1.0 | Jul 25, 2024 |
#218 in Date and time
5KB
Simplistic rate limiter
Useful in cases when you don't want to repeat an operation too often. For example, to prevent flooding the logs with the same message.
Example:
use std::{thread, time::Duration};
use ratelim::RateLimiter;
use tracing::warn;
fn main() {
let mut lim_warn_oddities = RateLimiter::new(Duration::from_millis(10));
let mut n = 0;
for i in 0..1000 {
lim_warn_oddities.run(|| {
if i % 2 != 0 {
warn!("{} is odd. Oh my!", i);
n += 1;
}
});
thread::sleep(Duration::from_micros(100));
}
assert!(0 < n && n < 10);
}
lib.rs
:
Simplistic rate limiter.
Examples
#
// We don't want to overwater plants. Twice a second should be fine?
let mut lim_water_plants = RateLimiter::new(Duration::from_millis(500));
let mut n = 0;
for _ in 0..5 {
lim_water_plants.run(|| {
println!("Watering plants... 🌱🔫");
n += 1;
});
thread::sleep(Duration::from_millis(200));
}
assert_eq!(n, 2);