#duration #once #interval #millis #expression #rate-limiting #macro

only_every

A simple rate-limiter macro: only_every!(Duration::from_millis(200), expensive_expression)

1 unstable release

0.1.0 Feb 12, 2022

#1654 in Rust patterns

Download history 276/week @ 2024-05-21 242/week @ 2024-05-28 165/week @ 2024-06-04 266/week @ 2024-06-11 136/week @ 2024-06-18 159/week @ 2024-06-25 159/week @ 2024-07-02 329/week @ 2024-07-09 273/week @ 2024-07-16 203/week @ 2024-07-23 230/week @ 2024-07-30 187/week @ 2024-08-06 195/week @ 2024-08-13 257/week @ 2024-08-20 339/week @ 2024-08-27 186/week @ 2024-09-03

1,029 downloads per month

Unlicense

10KB
119 lines

only_every

There are lots of rate-limiting crates that do lots of things, but sometimes you just want to evaluate an expression once every whatever interval, for example rate-limited logging. This crate exposes a macro:

only_every!(Duration::from_millis(100), expensive_thing)

This macro will evaluate the given expression at most every duration rounded up to the next ms. The limiter is global: if you use 20 threads, it's still only going to happen once every duration. The expression is not inside a closure and is consequently somewhat more transparent to the borrow checker (This probably doesn't matter to you; you can read it as "there aren't edge cases").

Enable the quanta feature for faster time-keeping at the cost of using the quanta crate, which requires a calibration period when executing the first rate-limited expression and an O(1) heap allocation. If you use quanta for other things, whoever gets there first handles the calibration.

If you need a bit more, e.g. storing these in structs instead of using the macro, there is also a OnlyEvery type. I suggest something like governor if you need more than "execute this once every x".

For completeness, internally we hold times in an i64 as ms since the process started. Behavior is undefined if your process runs for long enough that pt + interval > i64::MAX where pt is the uptime of the process and units are in ms. In other words, let me know if you have a billion years of continuous uptime and I'll fix it for you.

Dependencies

~0–1.9MB
~31K SLoC