Struct async_speed_limit::limiter::Limiter
source · pub struct Limiter<C: Clock = StandardClock> { /* private fields */ }
Expand description
A type to control the maximum speed limit of multiple streams.
When a Limiter
is cloned, the instances would share the same
queue. Multiple tasks can cooperatively respect a global speed limit
via clones. Cloning a Limiter
is cheap (equals to cloning two
Arc
s).
The speed limit is imposed by awaiting
consume()
. The method returns a future which
sleeps until rate falls below the limit.
Examples
Upload some small files atomically in parallel, while maintaining a global speed limit of 1 MiB/s.
use async_speed_limit::Limiter;
use futures_util::future::try_join_all;
let limiter = <Limiter>::new(1_048_576.0);
let processes = files
.iter()
.map(|file| {
let limiter = limiter.clone();
async move {
limiter.consume(file.len()).await;
upload(file).await?;
Ok(())
}
});
try_join_all(processes).await?;
Implementations§
source§impl<C: Clock> Limiter<C>
impl<C: Clock> Limiter<C>
sourcepub fn new(speed_limit: f64) -> Self
pub fn new(speed_limit: f64) -> Self
Creates a new speed limiter.
Use infinity to make the speed unlimited.
sourcepub fn set_speed_limit(&self, speed_limit: f64)
pub fn set_speed_limit(&self, speed_limit: f64)
Dynamically changes the speed limit. The new limit applies to all clones of this instance.
Use infinity to make the speed unlimited.
This change will not affect any tasks scheduled before this call.
sourcepub fn speed_limit(&self) -> f64
pub fn speed_limit(&self) -> f64
Returns the current speed limit.
This method returns infinity if the speed is unlimited.
sourcepub fn total_bytes_consumed(&self) -> usize
pub fn total_bytes_consumed(&self) -> usize
Obtains the total number of bytes consumed by this limiter so far.
If more than usize::MAX
bytes have been consumed, the count will wrap
around.
sourcepub fn reset_statistics(&self)
pub fn reset_statistics(&self)
Resets the total number of bytes consumed to 0.
sourcepub fn consume_duration(&self, byte_size: usize) -> Duration
pub fn consume_duration(&self, byte_size: usize) -> Duration
Consumes several bytes from the speed limiter, returns the duration needed to sleep to maintain the speed limit.
source§impl<C: BlockingClock> Limiter<C>
impl<C: BlockingClock> Limiter<C>
sourcepub fn blocking_consume(&self, byte_size: usize)
pub fn blocking_consume(&self, byte_size: usize)
Consumes several bytes, and sleeps the current thread to maintain the speed limit.
The consumption happens at the beginning, before the speed limit is
applied. This method blocks the current thread (e.g. using
std::thread::sleep()
given a StandardClock
), and must not be
used in async
context.
Prefer using this method instead of
futures_executor::block_on
(limiter.
consume
(size))
.