Debian Codegraph @

src/sources/timer.rs

raw symbols SCIP
1 //! Timer event source
2 //!
3 //! The [`Timer`] is an event source that will fire its event after a certain amount of time
4 //! specified at creation. Its timing is tracked directly by the event loop core logic, and it does
5 //! not consume any system resource.
6 //!
7 //! The timer precision depends on whether the loop was initialized in high-precision mode. If not,
8 //! you can expect precision of order of 1 millisecond, if you need sub-millisecond precision,
9 //! make sure you initialize the [`EventLoop`](crate::EventLoop) using
10 //! [`EventLoop::try_new_high_precision()`](crate::EventLoop::try_new_high_precision). Note also
11 //! that if you need to rely on good precision timers in general, you may need to enable realtime
12 //! features of your OS to ensure your thread is quickly woken up by the system scheduler.
13 //!
14 //! The provided event is an [`Instant`] representing the deadline for which this timer has fired
15 //! (which can be earlier than the current time depending on the event loop congestion).
16 //!
17 //! The callback associated with this event source is expected to return a [`TimeoutAction`], which
18 //! can be used to implement self-repeating timers by telling calloop to reprogram the same timer
19 //! for a later timeout after it has fired.
20
21 /*
22 * This module provides two main types:
23 *
24 * - `Timer` is the user-facing type that represents a timer event source
25 * - `TimerWheel` is an internal data structure for tracking registered timeouts, it is used by
26 * the polling logic in sys/mod.rs
27 */
28
29 use std::{
30 cell::RefCell,
31 collections::BinaryHeap,
32 rc::Rc,
33 task::Waker,
34 time::{Duration, Instant},
35 };
36
37 use crate::{EventSource, LoopHandle, Poll, PostAction, Readiness, Token, TokenFactory};
38
39 #[derive(Debug)]
40 struct Registration {
41 token: Token,
42 wheel: Rc<RefCell<TimerWheel>>,
43 counter: u32,
44 }
45
46 /// A timer event source
47 ///
48 /// When registered to the event loop, it will trigger an event once its deadline is reached.
49 /// If the deadline is in the past relative to the moment of its insertion in the event loop,
50 /// the `TImer` will trigger an event as soon as the event loop is dispatched.
51 #[derive(Debug)]
52 pub struct Timer {
53 registration: Option<Registration>,
54 deadline: Instant,
55 }
56
57 impl Timer {
58 /// Create a timer that will fire immediately when inserted in the event loop
59 pub fn immediate() -> Timer {
60 Self::from_deadline(Instant::now())
61 }
62
63 /// Create a timer that will fire after a given duration from now
64 pub fn from_duration(duration: Duration) -> Timer {
65 Self::from_deadline(Instant::now() + duration)
66 }
67
68 /// Create a timer that will fire at a given instant
69 pub fn from_deadline(deadline: Instant) -> Timer {
70 Timer {
71 registration: None,
72 deadline,
73 }
74 }
75
76 /// Changes the deadline of this timer to an [`Instant`]
77 ///
78 /// If the `Timer` is currently registered in the event loop, it needs to be
79 /// re-registered for this change to take effect.
80 pub fn set_deadline(&mut self, deadline: Instant) {
81 self.deadline = deadline;
82 }
83
84 /// Changes the deadline of this timer to a [`Duration`] from now
85 ///
86 /// If the `Timer` is currently registered in the event loop, it needs to be
87 /// re-registered for this change to take effect.
88 pub fn set_duration(&mut self, duration: Duration) {
89 self.set_deadline(Instant::now() + duration)
90 }
91
92 /// Get the current deadline of this `Timer`
93 pub fn current_deadline(&self) -> Instant {
94 self.deadline
95 }
96 }
97
98 impl EventSource for Timer {
99 type Event = Instant;
100 type Metadata = ();
101 type Ret = TimeoutAction;
102 type Error = std::io::Error;
103
104 fn process_events<F>(
105 &mut self,
106 _: Readiness,
107 token: Token,
108 mut callback: F,
109 ) -> Result<PostAction, Self::Error>
110 where
111 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
112 {
113 if let Some(ref registration) = self.registration {
114 if registration.token != token {
115 return Ok(PostAction::Continue);
116 }
117 let new_deadline = match callback(self.deadline, &mut ()) {
118 TimeoutAction::Drop => return Ok(PostAction::Remove),
119 TimeoutAction::ToInstant(instant) => instant,
120 TimeoutAction::ToDuration(duration) => Instant::now() + duration,
121 };
122 // If we received an event, we MUST have a valid counter value
123 registration.wheel.borrow_mut().insert_reuse(
124 registration.counter,
125 new_deadline,
126 registration.token,
127 );
128 self.deadline = new_deadline;
129 }
130 Ok(PostAction::Continue)
131 }
132
133 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
134 let wheel = poll.timers.clone();
135 let token = token_factory.token();
136 let counter = wheel.borrow_mut().insert(self.deadline, token);
137 self.registration = Some(Registration {
138 token,
139 wheel,
140 counter,
141 });
142 Ok(())
143 }
144
145 fn reregister(
146 &mut self,
147 poll: &mut Poll,
148 token_factory: &mut TokenFactory,
149 ) -> crate::Result<()> {
150 self.unregister(poll)?;
151 self.register(poll, token_factory)
152 }
153
154 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
155 if let Some(registration) = self.registration.take() {
156 poll.timers.borrow_mut().cancel(registration.counter);
157 }
158 Ok(())
159 }
160 }
161
162 /// Action to reschedule a timeout if necessary
163 #[derive(Debug)]
164 pub enum TimeoutAction {
165 /// Don't reschedule this timer
166 Drop,
167 /// Reschedule this timer to a given [`Instant`]
168 ToInstant(Instant),
169 /// Reschedule this timer to a given [`Duration`] in the future
170 ToDuration(Duration),
171 }
172
173 // Internal representation of a timeout registered in the TimerWheel
174 #[derive(Debug)]
175 struct TimeoutData {
176 deadline: Instant,
177 token: RefCell<Option<Token>>,
178 counter: u32,
179 }
180
181 // A data structure for tracking registered timeouts
182 #[derive(Debug)]
183 pub(crate) struct TimerWheel {
184 heap: BinaryHeap<TimeoutData>,
185 counter: u32,
186 }
187
188 impl TimerWheel {
189 pub(crate) fn new() -> TimerWheel {
190 TimerWheel {
191 heap: BinaryHeap::new(),
192 counter: 0,
193 }
194 }
195
196 pub(crate) fn insert(&mut self, deadline: Instant, token: Token) -> u32 {
197 self.heap.push(TimeoutData {
198 deadline,
199 token: RefCell::new(Some(token)),
200 counter: self.counter,
201 });
202 let ret = self.counter;
203 self.counter += 1;
204 ret
205 }
206
207 pub(crate) fn insert_reuse(&mut self, counter: u32, deadline: Instant, token: Token) {
208 self.heap.push(TimeoutData {
209 deadline,
210 token: RefCell::new(Some(token)),
211 counter,
212 });
213 }
214
215 pub(crate) fn cancel(&mut self, counter: u32) {
216 self.heap
217 .iter()
218 .find(|data| data.counter == counter)
219 .map(|data| data.token.take());
220 }
221
222 pub(crate) fn next_expired(&mut self, now: Instant) -> Option<(u32, Token)> {
223 loop {
224 // check if there is an expired item
225 if let Some(data) = self.heap.peek() {
226 if data.deadline > now {
227 return None;
228 }
229 // there is an expired timeout, continue the
230 // loop body
231 } else {
232 return None;
233 }
234
235 // There is an item in the heap, this unwrap cannot blow
236 let data = self.heap.pop().unwrap();
237 if let Some(token) = data.token.into_inner() {
238 return Some((data.counter, token));
239 }
240 // otherwise this timeout was cancelled, continue looping
241 }
242 }
243
244 pub(crate) fn next_deadline(&self) -> Option<std::time::Instant> {
245 self.heap.peek().map(|data| data.deadline)
246 }
247 }
248
249 // trait implementations for TimeoutData
250
251 impl std::cmp::Ord for TimeoutData {
252 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
253 // earlier values have priority
254 self.deadline.cmp(&other.deadline).reverse()
255 }
256 }
257
258 impl std::cmp::PartialOrd for TimeoutData {
259 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
260 Some(self.cmp(other))
261 }
262 }
263
264 // This impl is required for PartialOrd but actually never used
265 // and the type is private, so ignore its coverage
266 impl std::cmp::PartialEq for TimeoutData {
267 #[cfg_attr(coverage, no_coverage)]
268 fn eq(&self, other: &Self) -> bool {
269 self.deadline == other.deadline
270 }
271 }
272
273 impl std::cmp::Eq for TimeoutData {}
274
275 // Logic for timer futures
276
277 /// A future that resolves once a certain timeout is expired
278 pub struct TimeoutFuture {
279 deadline: Instant,
280 waker: Rc<RefCell<Option<Waker>>>,
281 }
282
283 impl std::fmt::Debug for TimeoutFuture {
284 #[cfg_attr(coverage, no_coverage)]
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 f.debug_struct("TimeoutFuture")
287 .field("deadline", &self.deadline)
288 .finish_non_exhaustive()
289 }
290 }
291
292 impl TimeoutFuture {
293 /// Create a future that resolves after a given duration
294 pub fn from_duration<Data>(handle: &LoopHandle<'_, Data>, duration: Duration) -> TimeoutFuture {
295 Self::from_deadline(handle, Instant::now() + duration)
296 }
297
298 /// Create a future that resolves at a given instant
299 pub fn from_deadline<Data>(handle: &LoopHandle<'_, Data>, deadline: Instant) -> TimeoutFuture {
300 let timer = Timer::from_deadline(deadline);
301 let waker = Rc::new(RefCell::new(None::<Waker>));
302 let waker2 = waker.clone();
303 handle
304 .insert_source(timer, move |_, &mut (), _| {
305 if let Some(waker) = waker2.borrow_mut().clone() {
306 waker.wake()
307 }
308 TimeoutAction::Drop
309 })
310 .unwrap();
311
312 TimeoutFuture { deadline, waker }
313 }
314 }
315
316 impl std::future::Future for TimeoutFuture {
317 type Output = ();
318
319 fn poll(
320 self: std::pin::Pin<&mut Self>,
321 cx: &mut std::task::Context<'_>,
322 ) -> std::task::Poll<Self::Output> {
323 if std::time::Instant::now() >= self.deadline {
324 return std::task::Poll::Ready(());
325 }
326 *self.waker.borrow_mut() = Some(cx.waker().clone());
327 std::task::Poll::Pending
328 }
329 }
330
331 #[cfg(test)]
332 mod tests {
333 use super::*;
334 use crate::*;
335 use std::time::Duration;
336
337 #[test]
338 fn simple_timer() {
339 let mut event_loop = EventLoop::try_new().unwrap();
340
341 let mut dispatched = false;
342
343 event_loop
344 .handle()
345 .insert_source(
346 Timer::from_duration(Duration::from_millis(100)),
347 |_, &mut (), dispatched| {
348 *dispatched = true;
349 TimeoutAction::Drop
350 },
351 )
352 .unwrap();
353
354 event_loop
355 .dispatch(Some(Duration::ZERO), &mut dispatched)
356 .unwrap();
357 // not yet dispatched
358 assert!(!dispatched);
359
360 event_loop
361 .dispatch(Some(Duration::from_millis(150)), &mut dispatched)
362 .unwrap();
363 // now dispatched
364 assert!(dispatched);
365 }
366
367 #[test]
368 fn simple_timer_instant() {
369 let mut event_loop = EventLoop::try_new().unwrap();
370
371 let mut dispatched = false;
372
373 event_loop
374 .handle()
375 .insert_source(
376 Timer::from_duration(Duration::from_millis(100)),
377 |_, &mut (), dispatched| {
378 *dispatched = true;
379 TimeoutAction::Drop
380 },
381 )
382 .unwrap();
383
384 event_loop
385 .dispatch(Some(Duration::from_millis(150)), &mut dispatched)
386 .unwrap();
387 // now dispatched
388 assert!(dispatched);
389 }
390
391 #[test]
392 fn immediate_timer() {
393 let mut event_loop = EventLoop::try_new().unwrap();
394
395 let mut dispatched = false;
396
397 event_loop
398 .handle()
399 .insert_source(Timer::immediate(), |_, &mut (), dispatched| {
400 *dispatched = true;
401 TimeoutAction::Drop
402 })
403 .unwrap();
404
405 event_loop
406 .dispatch(Some(Duration::ZERO), &mut dispatched)
407 .unwrap();
408 // now dispatched
409 assert!(dispatched);
410 }
411
412 // We cannot actually test high precision timers, as they are only high precision in release mode
413 // This test is here to ensure that the high-precision codepath are executed and work as intended
414 // even if we cannot test if they are actually high precision
415 #[test]
416 fn high_precision_timer() {
417 let mut event_loop = EventLoop::try_new_high_precision().unwrap();
418
419 let mut dispatched = false;
420
421 event_loop
422 .handle()
423 .insert_source(
424 Timer::from_duration(Duration::from_millis(100)),
425 |_, &mut (), dispatched| {
426 *dispatched = true;
427 TimeoutAction::Drop
428 },
429 )
430 .unwrap();
431
432 event_loop
433 .dispatch(Some(Duration::ZERO), &mut dispatched)
434 .unwrap();
435 // not yet dispatched
436 assert!(!dispatched);
437
438 event_loop
439 .dispatch(Some(Duration::from_micros(10200)), &mut dispatched)
440 .unwrap();
441 // yet not dispatched
442 assert!(!dispatched);
443
444 event_loop
445 .dispatch(Some(Duration::from_millis(100)), &mut dispatched)
446 .unwrap();
447 // now dispatched
448 assert!(dispatched);
449 }
450
451 #[test]
452 fn cancel_timer() {
453 let mut event_loop = EventLoop::try_new().unwrap();
454
455 let mut dispatched = false;
456
457 let token = event_loop
458 .handle()
459 .insert_source(
460 Timer::from_duration(Duration::from_millis(100)),
461 |_, &mut (), dispatched| {
462 *dispatched = true;
463 TimeoutAction::Drop
464 },
465 )
466 .unwrap();
467
468 event_loop
469 .dispatch(Some(Duration::ZERO), &mut dispatched)
470 .unwrap();
471 // not yet dispatched
472 assert!(!dispatched);
473
474 event_loop.handle().remove(token);
475
476 event_loop
477 .dispatch(Some(Duration::from_millis(150)), &mut dispatched)
478 .unwrap();
479 // still not dispatched
480 assert!(!dispatched);
481 }
482
483 #[test]
484 fn repeating_timer() {
485 let mut event_loop = EventLoop::try_new().unwrap();
486
487 let mut dispatched = 0;
488
489 event_loop
490 .handle()
491 .insert_source(
492 Timer::from_duration(Duration::from_millis(500)),
493 |_, &mut (), dispatched| {
494 *dispatched += 1;
495 TimeoutAction::ToDuration(Duration::from_millis(500))
496 },
497 )
498 .unwrap();
499
500 event_loop
501 .dispatch(Some(Duration::from_millis(250)), &mut dispatched)
502 .unwrap();
503 assert_eq!(dispatched, 0);
504
505 event_loop
506 .dispatch(Some(Duration::from_millis(510)), &mut dispatched)
507 .unwrap();
508 assert_eq!(dispatched, 1);
509
510 event_loop
511 .dispatch(Some(Duration::from_millis(510)), &mut dispatched)
512 .unwrap();
513 assert_eq!(dispatched, 2);
514
515 event_loop
516 .dispatch(Some(Duration::from_millis(510)), &mut dispatched)
517 .unwrap();
518 assert_eq!(dispatched, 3);
519 }
520
521 #[cfg(feature = "executor")]
522 #[test]
523 fn timeout_future() {
524 let mut event_loop = EventLoop::try_new().unwrap();
525
526 let mut dispatched = 0;
527
528 let timeout_1 =
529 TimeoutFuture::from_duration(&event_loop.handle(), Duration::from_millis(500));
530 let timeout_2 =
531 TimeoutFuture::from_duration(&event_loop.handle(), Duration::from_millis(1500));
532
533 let (exec, sched) = crate::sources::futures::executor().unwrap();
534 event_loop
535 .handle()
536 .insert_source(exec, move |(), &mut (), got| {
537 *got += 1;
538 })
539 .unwrap();
540
541 sched.schedule(timeout_1).unwrap();
542 sched.schedule(timeout_2).unwrap();
543
544 // We do a 0-timeout dispatch after every regular dispatch to let the timeout triggers
545 // flow back to the executor
546
547 event_loop
548 .dispatch(Some(Duration::ZERO), &mut dispatched)
549 .unwrap();
550 event_loop
551 .dispatch(Some(Duration::ZERO), &mut dispatched)
552 .unwrap();
553 assert_eq!(dispatched, 0);
554
555 event_loop
556 .dispatch(Some(Duration::from_millis(1000)), &mut dispatched)
557 .unwrap();
558 event_loop
559 .dispatch(Some(Duration::ZERO), &mut dispatched)
560 .unwrap();
561 assert_eq!(dispatched, 1);
562
563 event_loop
564 .dispatch(Some(Duration::from_millis(1100)), &mut dispatched)
565 .unwrap();
566 event_loop
567 .dispatch(Some(Duration::ZERO), &mut dispatched)
568 .unwrap();
569 assert_eq!(dispatched, 2);
570 }
571 }