41 lines
852 B
Rust
41 lines
852 B
Rust
use core::time::Duration;
|
|
use std::time::Instant;
|
|
|
|
#[derive(Debug)]
|
|
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.tick() {
|
|
f();
|
|
}
|
|
}
|
|
|
|
pub fn tick(&mut self) -> bool {
|
|
if self.last_run.elapsed() >= self.duration {
|
|
self.last_run = Instant::now();
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
}
|