Skip to main content

tokio_timerd/
delay.rs

1use crate::timer::Timer;
2use futures_core::ready;
3use std::future::Future;
4use std::io::Error as IoError;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7use std::time::Instant;
8
9/// A future that completes at a specified instant.
10///
11/// `Delay` uses the operating system's native timer facility where available
12/// and returns an error if the timer cannot be created or polled.
13pub struct Delay {
14    timer: Timer,
15    deadline: Instant,
16    initialized: bool,
17}
18
19impl Delay {
20    /// Creates a new `Delay` that completes at `deadline`.
21    pub fn new(deadline: Instant) -> Result<Self, IoError> {
22        Ok(Delay {
23            timer: Timer::new()?,
24            deadline,
25            initialized: false,
26        })
27    }
28
29    /// Returns the instant at which the future will complete.
30    pub fn deadline(&self) -> Instant {
31        self.deadline
32    }
33
34    /// Returns `true` once `deadline` has been reached.
35    pub fn is_elapsed(&self) -> bool {
36        self.deadline <= Instant::now()
37    }
38
39    /// Resets the delay to a new deadline.
40    pub fn reset(&mut self, deadline: Instant) {
41        self.timer.disarm();
42        self.deadline = deadline;
43        self.initialized = false;
44    }
45}
46
47impl Future for Delay {
48    type Output = Result<(), IoError>;
49
50    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
51        if !self.initialized {
52            let deadline = self.deadline;
53            self.timer.arm(deadline)?;
54            self.initialized = true;
55        }
56        ready!(self.timer.poll_expired(cx))?;
57        Poll::Ready(Ok(()))
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use std::time::Duration;
65
66    #[tokio::test]
67    async fn delay_zero_duration() -> Result<(), std::io::Error> {
68        let now = Instant::now();
69        let delay = Delay::new(Instant::now())?;
70        delay.await?;
71        assert!(now.elapsed() < Duration::from_secs(1));
72        Ok(())
73    }
74
75    #[tokio::test]
76    async fn delay_works() {
77        let now = Instant::now();
78        let delay = Delay::new(now + Duration::from_millis(10)).unwrap();
79        delay.await.unwrap();
80        assert!(now.elapsed() < Duration::from_secs(1));
81    }
82
83    #[test]
84    fn sleep_overflow_is_rejected() {
85        assert!(crate::try_sleep(Duration::MAX).is_err());
86    }
87
88    #[tokio::test]
89    async fn delay_reset_rearms_timer() -> Result<(), std::io::Error> {
90        let start = Instant::now();
91        let mut delay = Delay::new(start + Duration::from_secs(60))?;
92        delay.reset(start + Duration::from_millis(10));
93        delay.await?;
94        assert!(start.elapsed() < Duration::from_secs(1));
95        Ok(())
96    }
97
98    #[tokio::test]
99    async fn dropping_pending_delay_is_safe() -> Result<(), std::io::Error> {
100        let delay = Delay::new(Instant::now() + Duration::from_secs(60))?;
101        drop(delay);
102        Ok(())
103    }
104
105    #[tokio::test]
106    async fn try_sleep_works() -> Result<(), std::io::Error> {
107        crate::try_sleep(Duration::from_millis(1))?.await
108    }
109
110    #[tokio::test]
111    async fn delay_reports_elapsed_state() -> Result<(), std::io::Error> {
112        let mut delay = Delay::new(Instant::now() + Duration::from_millis(10))?;
113        assert!(!delay.is_elapsed());
114
115        delay.reset(Instant::now() - Duration::from_millis(1));
116        assert!(delay.is_elapsed());
117
118        delay.reset(Instant::now() + Duration::from_millis(10));
119        assert!(!delay.is_elapsed());
120        Ok(())
121    }
122}