Skip to main content

tokio_timerd/
lib.rs

1#![deny(missing_docs)]
2#![forbid(unsafe_op_in_unsafe_fn)]
3
4//! OS-backed timers for Tokio.
5//!
6//! The active backends are:
7//!
8//! * Linux and Android: [`timerfd`](https://man7.org/linux/man-pages/man2/timerfd_create.2.html).
9//! * Windows: a high-resolution waitable timer when supported, with a
10//!   standard waitable-timer fallback on older Windows versions.
11//! * macOS, iOS, and BSD: `kqueue` with `EVFILT_TIMER`; NetBSD and OpenBSD
12//!   currently fall back to millisecond granularity.
13//! * Other platforms: a Tokio timer-wheel fallback.
14//!
15//! "High resolution" describes the operating-system timer facility and the
16//! granularity it can represent; it is not a promise that a task is polled at
17//! the requested deadline. Resolution is only the timer's representable step:
18//!
19//! * Deadline error is the difference between the actual and requested
20//!   wakeup. It includes timer delivery, OS scheduling, task wakeup, and load.
21//! * Jitter is variation in that error between wakeups. Low jitter does not
22//!   imply low absolute latency.
23//! * Drift is accumulated error over repeated periods. `Interval` re-arms
24//!   against an absolute schedule to avoid unbounded drift, but it cannot
25//!   remove scheduler-induced latency.
26//!
27//! These APIs do not provide hard real-time guarantees.
28//!
29//! * [`Delay`]: a future that completes at a specified instant.
30//! * [`Interval`]: a stream that yields at fixed intervals.
31//! * [`DelayQueue`]: a queue that multiplexes many deadlines over one timer.
32//! * [`sleep`] and [`try_sleep`]: convenience functions that create a [`Delay`].
33//!
34//! Timer constructors must be called while a Tokio runtime is active.
35//!
36//! On Linux, the `realtime` and `boottime` features select an alternative
37//! `timerfd` clock. With neither feature enabled, the monotonic clock is used.
38//! These features have no effect on other platforms.
39
40use std::io;
41use std::time::{Duration, Instant};
42
43#[cfg(all(feature = "realtime", feature = "boottime"))]
44compile_error!("features `realtime` and `boottime` are mutually exclusive");
45
46mod delay;
47mod delay_queue;
48mod interval;
49mod timer;
50
51pub use delay::Delay;
52pub use delay_queue::{DelayQueue, Expired, Key};
53pub use interval::Interval;
54
55#[cfg(any(target_os = "linux", target_os = "android"))]
56pub use timerfd::ClockId;
57
58#[cfg(any(target_os = "linux", target_os = "android"))]
59use std::io::{Error, Result};
60#[cfg(any(target_os = "linux", target_os = "android"))]
61use std::os::unix::io::{AsRawFd, RawFd};
62#[cfg(any(target_os = "linux", target_os = "android"))]
63use std::pin::Pin;
64#[cfg(any(target_os = "linux", target_os = "android"))]
65use std::task::{Context, Poll};
66
67#[cfg(any(target_os = "linux", target_os = "android"))]
68use futures_core::ready;
69#[cfg(any(target_os = "linux", target_os = "android"))]
70use timerfd::{SetTimeFlags, TimerFd as InnerTimerFd, TimerState};
71#[cfg(any(target_os = "linux", target_os = "android"))]
72use tokio::io::unix::AsyncFd;
73#[cfg(any(target_os = "linux", target_os = "android"))]
74use tokio::io::{AsyncRead, Interest, ReadBuf};
75
76/// A low-level Linux `timerfd` integrated with the Tokio reactor.
77///
78/// This type is available only on Linux and Android. Most applications
79/// should use [`Delay`] or [`Interval`] instead.
80#[cfg(any(target_os = "linux", target_os = "android"))]
81pub struct TimerFd(AsyncFd<InnerTimerFd>);
82
83#[cfg(any(target_os = "linux", target_os = "android"))]
84impl TimerFd {
85    /// Creates and registers a non-blocking `timerfd` using `clock`.
86    pub fn new(clock: ClockId) -> io::Result<Self> {
87        let fd = InnerTimerFd::new_custom(clock, true, true)?;
88        let inner = AsyncFd::with_interest(fd, Interest::READABLE)?;
89        Ok(TimerFd(inner))
90    }
91
92    fn set_state(&mut self, state: TimerState, flags: SetTimeFlags) -> TimerState {
93        self.0.get_mut().set_state(state, flags)
94    }
95}
96
97#[cfg(any(target_os = "linux", target_os = "android"))]
98impl AsRawFd for TimerFd {
99    fn as_raw_fd(&self) -> RawFd {
100        self.0.as_raw_fd()
101    }
102}
103
104#[cfg(any(target_os = "linux", target_os = "android"))]
105fn read_u64(fd: RawFd) -> Result<u64> {
106    loop {
107        let mut buf = [0u8; 8];
108        let rv = unsafe {
109            // SAFETY: `fd` is owned by the TimerFd and `buf` has exactly
110            // eight bytes, the size required by timerfd reads.
111            libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len())
112        };
113
114        if rv == buf.len() as isize {
115            return Ok(u64::from_ne_bytes(buf));
116        }
117        if rv < 0 {
118            let err = Error::last_os_error();
119            if err.kind() == io::ErrorKind::Interrupted {
120                continue;
121            }
122            return Err(err);
123        }
124
125        return Err(Error::new(
126            io::ErrorKind::UnexpectedEof,
127            "timerfd returned an incomplete expiration count",
128        ));
129    }
130}
131
132#[cfg(any(target_os = "linux", target_os = "android"))]
133impl AsyncRead for TimerFd {
134    fn poll_read(
135        mut self: Pin<&mut Self>,
136        cx: &mut Context<'_>,
137        buf: &mut ReadBuf<'_>,
138    ) -> Poll<Result<()>> {
139        if buf.remaining() < 8 {
140            return Poll::Ready(Err(Error::new(
141                io::ErrorKind::InvalidInput,
142                "TimerFd requires at least 8 bytes of buffer space",
143            )));
144        }
145
146        let inner = self.as_mut();
147        let fd = inner.0.as_raw_fd();
148
149        loop {
150            let mut guard = ready!(inner.0.poll_read_ready(cx))?;
151            match guard.try_io(|_| read_u64(fd)) {
152                Ok(res) => {
153                    let num = res?;
154                    buf.put_slice(&num.to_ne_bytes());
155                    break;
156                }
157                Err(_) => continue,
158            }
159        }
160        Poll::Ready(Ok(()))
161    }
162}
163
164/// Creates a future that completes in `duration` from now.
165///
166/// This convenience function panics if the operating-system timer cannot be
167/// created. Use [`try_sleep`] to handle that error explicitly.
168pub fn sleep(duration: Duration) -> Delay {
169    try_sleep(duration).expect("can't create delay")
170}
171
172/// Tries to create a future that completes in `duration` from now.
173pub fn try_sleep(duration: Duration) -> io::Result<Delay> {
174    let deadline = Instant::now().checked_add(duration).ok_or_else(|| {
175        io::Error::new(
176            io::ErrorKind::InvalidInput,
177            "sleep duration exceeds the supported clock range",
178        )
179    })?;
180    Delay::new(deadline)
181}
182
183#[cfg(all(test, any(target_os = "linux", target_os = "android")))]
184mod timerfd_tests {
185    use super::*;
186    use std::future::poll_fn;
187
188    #[tokio::test]
189    async fn short_read_buffer_is_rejected() {
190        let mut timer = TimerFd::new(ClockId::Monotonic).unwrap();
191        let mut buffer = [0_u8; 1];
192        let mut read_buffer = ReadBuf::new(&mut buffer);
193        let err = poll_fn(|cx| Pin::new(&mut timer).poll_read(cx, &mut read_buffer))
194            .await
195            .unwrap_err();
196        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
197    }
198}
199
200#[cfg(any(target_os = "linux", target_os = "android"))]
201#[cfg(feature = "realtime")]
202fn get_clock() -> ClockId {
203    ClockId::Realtime
204}
205
206#[cfg(any(target_os = "linux", target_os = "android"))]
207#[cfg(feature = "boottime")]
208fn get_clock() -> ClockId {
209    ClockId::Boottime
210}
211
212#[cfg(any(target_os = "linux", target_os = "android"))]
213#[cfg(not(any(feature = "boottime", feature = "realtime")))]
214fn get_clock() -> ClockId {
215    ClockId::Monotonic
216}