use std::time::{Duration, Instant};
use hala_lockfree::timewheel::HashedTimeWheel;
use crate::Token;
pub(super) struct MioTimer {
start_instant: Option<Instant>,
pub(super) duration: Duration,
tick_duration: Option<Duration>,
timewheel_ticks: Option<u64>,
}
impl MioTimer {
pub(super) fn new(duration: Duration) -> Self {
Self {
start_instant: None,
duration,
timewheel_ticks: None,
tick_duration: None,
}
}
pub(super) fn is_started(&self) -> bool {
self.start_instant.is_some()
}
pub(super) fn start(
&mut self,
token: Token,
tick_duration: Duration,
timewheel: &HashedTimeWheel<Token>,
) -> bool {
self.start_instant = Some(Instant::now());
self.tick_duration = Some(tick_duration);
self.timewheel_ticks = timewheel.new_timer(token, self.duration);
self.timewheel_ticks.is_some()
}
pub(super) fn is_expired(&self) -> bool {
if let Some(start_instant) = self.start_instant {
let elapsed = start_instant.elapsed();
if elapsed >= self.duration {
return true;
}
if self.duration - elapsed < self.tick_duration.expect("Must call start first") {
return true;
}
return false;
} else {
false
}
}
}