Crate ratelimit [−] [src]
A token bucket ratelimiter for rust which can be used by either a single thread or shared across threads using a mpsc synchronous channel
Goals
- a simple token bucket ratelimiter
- usable in single or multi thread code
Future work
- consider additional types of ratelimiters
Usage
Construct a new Ratelimit
and call block between actions. For multi-thread
clone the channel sender to pass to the threads, in a separate thread, call
run on the Ratelimit
in a tight loop.
Example
Construct Ratelimit
and use in single and then multi-thread modes
extern crate time; extern crate ratelimit; use std::thread; use std::sync::mpsc; // create a Ratelimit let capacity = 1; // bucket can hold 10 tokens let start = time::precise_time_ns(); // start time let interval = 1_000_000_000; // 1 second => 1 Hz let quantum = 1; // 1 token per interval => 1 tokens/s let mut ratelimit = ratelimit::Ratelimit::new( capacity, start, interval, quantum ).unwrap(); // count down to ignition println!("Count-down...."); for i in 0..5 { println!("T-Minus {}", (5 - i)); ratelimit.block(1); } println!("Ignition!"); // clone the sender from Ratelimit let sender = ratelimit.clone_sender(); // create ratelimited threads for i in 0..2 { let s = sender.clone(); thread::spawn(move || { for x in 0..5 { s.send(()); println!("."); } }); } // run the ratelimiter thread::spawn(move || { loop { ratelimit.run(); } });
Structs
Ratelimit |