Skip to main content

tokio_timerd/
interval.rs

1use crate::timer::Timer;
2use futures_core::{ready, Stream};
3use std::convert::TryFrom;
4use std::io::Error as IoError;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7use std::time::{Duration, Instant};
8
9/// A stream that yields at fixed intervals.
10///
11/// Missed ticks are skipped: after a scheduling delay, the next deadline is
12/// advanced to the next period boundary at or after the current time.
13pub struct Interval {
14    timer: Timer,
15    next: Instant,
16    duration: Duration,
17}
18
19impl Interval {
20    /// Creates a new `Interval` whose first tick is at `at`, followed by
21    /// ticks every `duration`.
22    ///
23    /// # Panics
24    ///
25    /// Panics if `duration` is zero.
26    pub fn new(at: Instant, duration: Duration) -> Result<Interval, IoError> {
27        assert!(
28            duration > Duration::new(0, 0),
29            "`duration` must be non-zero."
30        );
31        Ok(Interval {
32            timer: Timer::new()?,
33            next: at,
34            duration,
35        })
36    }
37
38    /// Creates a new `Interval` whose first tick is `duration` from now.
39    ///
40    /// # Panics
41    ///
42    /// Panics if `duration` is zero.
43    pub fn new_interval(duration: Duration) -> Result<Interval, IoError> {
44        let at = Instant::now().checked_add(duration).ok_or_else(|| {
45            IoError::new(
46                std::io::ErrorKind::InvalidInput,
47                "interval duration exceeds the supported clock range",
48            )
49        })?;
50        Self::new(at, duration)
51    }
52}
53
54impl Stream for Interval {
55    type Item = Result<(), IoError>;
56
57    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
58        while Instant::now() < self.next {
59            let next = self.next;
60            self.timer.arm(next)?;
61            ready!(self.timer.poll_expired(cx))?;
62        }
63
64        let fired = self.next;
65        self.next = next_deadline(fired, Instant::now(), self.duration)?;
66        Poll::Ready(Some(Ok(())))
67    }
68}
69
70fn next_deadline(fired: Instant, now: Instant, duration: Duration) -> Result<Instant, IoError> {
71    let next = fired.checked_add(duration).ok_or_else(schedule_overflow)?;
72    if now < next {
73        return Ok(next);
74    }
75
76    let elapsed = now.saturating_duration_since(fired).as_nanos();
77    let periods = elapsed / duration.as_nanos().max(1) + 1;
78    let periods = u32::try_from(periods).unwrap_or(u32::MAX);
79    fired
80        .checked_add(duration.saturating_mul(periods))
81        .ok_or_else(schedule_overflow)
82}
83
84fn schedule_overflow() -> IoError {
85    IoError::new(
86        std::io::ErrorKind::InvalidInput,
87        "interval deadline exceeds the supported clock range",
88    )
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use futures::stream::StreamExt;
95
96    #[tokio::test]
97    async fn interval_works() {
98        let mut interval = Interval::new_interval(Duration::from_millis(1)).unwrap();
99
100        let start = Instant::now();
101        for _ in 0..5 {
102            interval.next().await.unwrap().unwrap();
103        }
104        assert!(start.elapsed() < Duration::from_secs(1));
105    }
106
107    #[tokio::test]
108    async fn long_interval_works() {
109        let mut interval = Interval::new_interval(Duration::from_millis(20)).unwrap();
110
111        // The first tick may already be due if the scheduler delays this task
112        // before its first poll. Measure the following periods instead.
113        interval.next().await.unwrap().unwrap();
114
115        for _ in 0..2 {
116            let before = Instant::now();
117            interval.next().await.unwrap().unwrap();
118            let elapsed = before.elapsed();
119            assert!(elapsed >= Duration::from_millis(10));
120            assert!(elapsed < Duration::from_secs(1));
121        }
122    }
123
124    #[test]
125    fn overflow_is_rejected() {
126        assert!(Interval::new_interval(Duration::MAX).is_err());
127    }
128
129    #[test]
130    fn missed_ticks_advance_to_next_boundary() {
131        let fired = Instant::now();
132        let duration = Duration::from_millis(100);
133        let now = fired + Duration::from_millis(250);
134        assert_eq!(
135            next_deadline(fired, now, duration).unwrap(),
136            fired + Duration::from_millis(300)
137        );
138    }
139}