Crates.io | throttle_my_fn |
lib.rs | throttle_my_fn |
version | 0.2.6 |
source | src |
created_at | 2021-11-17 12:48:45.938029 |
updated_at | 2022-08-16 12:46:34.500593 |
description | Throttle your functions |
homepage | https://github.com/fredmorcos/throttle_my_fn |
repository | https://github.com/fredmorcos/throttle_my_fn |
max_upload_size | |
id | 483317 |
size | 21,993 |
throttle_my_fn
: A Rust attribute macro to throttle the execution of functionsthrottle_my_fn
is a Rust attribute macro to limit a function's number of runs over a
specified period of time, even when called from multiple threads.
The primary use-case for this attribute macro is rate-limiting, e.g. to avoid hammering an online service or to avoid serving too many requests over a period of time.
The macro works by rewriting the function and prefixing it with the necessary book-keeping
for throttling (see Usage
below). The resulting function is thread-safe.
Add the necessary dependencies to your Cargo.toml
:
[dependencies]
throttle_my_fn = "0.2"
parking_lot = "0.11"
Or, using cargo add
:
$ cargo add throttle_my_fn
$ cargo add parking_lot
Include the macro:
use throttle_my_fn::throttle;
Annotate the functions you want to throttle:
#[throttle(10, Duration::from_secs(1))]
pub(crate) fn run_10_times_per_second(arg: &str) -> String {
...
}
#[throttle(1, Duration::from_millis(100))]
pub(crate) fn run_once_per_100_milliseconds(arg: &str) -> String {
...
}
Note that the function signatures are modified to wrap the return type in an Option
,
like so:
pub(crate) fn run_10_times_per_second(arg: &str) -> Option<String> {
...
}
pub(crate) fn run_once_per_100_milliseconds(arg: &str) -> Option<String> {
...
}
The Option<T>
returned signifies whether the function executed or not.
0.2.6
0.2.5
0.2.4
parking_lot
as a dependency.0.2.3
0.2.2
0.2.1
@not-matthias
from the Rust Linz Discord server for feedback.0.2.0
MaybeUninit
and AtomicBool
with parking_lot::Mutex
and
parking_lot::const_mutex
.@mejrs
and @veber-alex
from the Rust Discord server for feedback.0.1.0