31 lines
690 B
Rust
31 lines
690 B
Rust
|
use std::time::{Instant, Duration};
|
||
|
|
||
|
pub struct Periodically {
|
||
|
last_run: Instant,
|
||
|
duration: Duration
|
||
|
}
|
||
|
|
||
|
impl Periodically {
|
||
|
pub fn new(duration: Duration) -> Self {
|
||
|
Self {
|
||
|
last_run: Instant::now(),
|
||
|
duration: duration
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn new_every_n_seconds(seconds: u64) -> Self {
|
||
|
Self::new(Duration::new(seconds, 0))
|
||
|
}
|
||
|
|
||
|
pub fn new_every_n_ms(milliseconds: u32) -> Self {
|
||
|
Self::new(Duration::new(0, milliseconds*1000))
|
||
|
}
|
||
|
|
||
|
pub fn run<F>(&mut self, f: F) where F: FnOnce() {
|
||
|
if self.last_run.elapsed() >= self.duration {
|
||
|
f();
|
||
|
self.last_run = Instant::now();
|
||
|
}
|
||
|
}
|
||
|
}
|