4 releases

0.2.1 Feb 27, 2025
0.2.0 Feb 27, 2025
0.1.1 Jul 25, 2024
0.1.0 Jul 25, 2024

#255 in Date and time

Download history 40/week @ 2024-12-25 16/week @ 2025-01-01 41/week @ 2025-01-08 77/week @ 2025-01-15 11/week @ 2025-01-22 41/week @ 2025-02-12 6/week @ 2025-02-19 357/week @ 2025-02-26 49/week @ 2025-03-05 22/week @ 2025-03-12 63/week @ 2025-03-19 51/week @ 2025-03-26 68/week @ 2025-04-02 25/week @ 2025-04-09

211 downloads per month

MIT license

6KB
58 lines

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);

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);
}

No runtime deps