Skip to content

Commit

Permalink
Re-work time adjustments
Browse files Browse the repository at this point in the history
  • Loading branch information
DoumanAsh committed Mar 21, 2024
1 parent 86b0e4f commit eab97d2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub struct Interval<T=PlatformTimer> {
timer: T,
///Timer interval, change to this value will be reflected on next restart of timer.
pub interval: time::Duration,
finish_at: time::Instant,
}

impl Interval {
Expand All @@ -50,6 +51,7 @@ impl<T: Timer> Interval<T> {
pub fn new(interval: time::Duration) -> Self {
Self {
timer: T::new(interval),
finish_at: time::Instant::now() + interval,
interval,
}
}
Expand All @@ -62,7 +64,12 @@ impl<T: Timer> Interval<T> {

///Restarts interval
pub fn restart(&mut self) {
let interval = self.interval;
let now = time::Instant::now();

let interval = match now.checked_duration_since(self.finish_at) {
Some(delayed) => self.interval - time::Duration::from_nanos((delayed.as_nanos() % self.interval.as_nanos()) as _),
None => self.interval
};
self.timer.restart(interval);
}

Expand Down
6 changes: 3 additions & 3 deletions tests/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async fn test_interval() {
}

async fn test_interval_average(num_runs: usize, interval: time::Duration) {
let mut times = Vec::with_capacity(6000);
let mut times = Vec::with_capacity(num_runs);

println!("interval={:?}", interval);
let mut timer = async_timer::interval(interval);
Expand Down Expand Up @@ -52,10 +52,10 @@ async fn test_interval_average(num_runs: usize, interval: time::Duration) {

#[tokio::test]
async fn test_average_of_small_interval() {
test_interval_average(600, time::Duration::from_secs_f32(1. / 120.)).await;
test_interval_average(6000, time::Duration::from_secs_f32(1. / 120.)).await;
}

#[tokio::test]
async fn test_average_of_mid_interval() {
test_interval_average(10, time::Duration::from_secs_f32(135. / 120.)).await;
test_interval_average(60, time::Duration::from_secs_f32(135. / 120.)).await;
}

0 comments on commit eab97d2

Please sign in to comment.