renderbug/src/time.rs

32 lines
720 B
Rust
Raw Normal View History

use std::time::{Instant, Duration};
2024-11-02 15:18:41 +01:00
#[derive(Debug, Clone, Copy)]
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();
}
}
}