embassy_time/timer.rs
1use core::future::{Future, poll_fn};
2use core::pin::Pin;
3use core::task::{Context, Poll};
4
5use futures_core::Stream;
6use futures_core::stream::FusedStream;
7
8use crate::{Duration, Instant};
9
10/// Error returned by [`with_timeout`] and [`with_deadline`] on timeout.
11#[derive(Debug, Clone, PartialEq, Eq)]
12#[cfg_attr(feature = "defmt", derive(defmt::Format))]
13pub struct TimeoutError;
14
15/// Runs a given future with a timeout.
16///
17/// If the future completes before the timeout, its output is returned. Otherwise, on timeout,
18/// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
19///
20/// ## Panics
21///
22/// Panics if the computed instant overflows.
23/// Avoid panics with [`try_with_timeout()`].
24pub fn with_timeout<F: Future>(timeout: impl Into<Duration>, fut: F) -> TimeoutFuture<F> {
25 let timeout = timeout.into();
26 with_deadline(Instant::now() + timeout, fut)
27}
28
29/// Tries to run a given future with a timeout.
30///
31/// If the future completes before the timeout, its output is returned. Otherwise, on timeout,
32/// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
33///
34/// This is a panic-free version of [`with_timeout`].
35pub fn try_with_timeout<F: Future>(timeout: impl Into<Duration>, fut: F) -> Option<TimeoutFuture<F>> {
36 let timeout = timeout.into();
37 Some(with_deadline(Instant::now().checked_add(timeout)?, fut))
38}
39
40/// Runs a given future with a deadline time.
41///
42/// If the future completes before the deadline, its output is returned. Otherwise, on timeout,
43/// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
44pub fn with_deadline<F: Future>(at: Instant, fut: F) -> TimeoutFuture<F> {
45 TimeoutFuture {
46 timer: Timer::at(at),
47 fut,
48 }
49}
50
51/// Provides functions to run a given future with a timeout or a deadline.
52pub trait WithTimeout: Sized {
53 /// Output type of the future.
54 type Output;
55
56 /// Runs a given future with a timeout.
57 ///
58 /// If the future completes before the timeout, its output is returned. Otherwise, on timeout,
59 /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
60 ///
61 /// ## Panics
62 ///
63 /// Panics if the computed instant overflows.
64 /// Avoid panics with [`WithTimeout::try_with_timeout()`].
65 fn with_timeout(self, timeout: impl Into<Duration>) -> TimeoutFuture<Self> {
66 let timeout = timeout.into();
67 self.with_deadline(Instant::now() + timeout)
68 }
69
70 /// Tries to run a given future with a timeout.
71 ///
72 /// If the future completes before the timeout, its output is returned. Otherwise, on timeout,
73 /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
74 ///
75 /// This is a panic-free [`WithTimeout::with_timeout()`].
76 fn try_with_timeout(self, timeout: impl Into<Duration>) -> Option<TimeoutFuture<Self>> {
77 let timeout = timeout.into();
78 Some(self.with_deadline(Instant::now().checked_add(timeout)?))
79 }
80
81 /// Runs a given future with a deadline time.
82 ///
83 /// If the future completes before the deadline, its output is returned. Otherwise, on timeout,
84 /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
85 fn with_deadline(self, at: Instant) -> TimeoutFuture<Self>;
86}
87
88impl<F: Future> WithTimeout for F {
89 type Output = F::Output;
90
91 fn with_deadline(self, at: Instant) -> TimeoutFuture<Self> {
92 with_deadline(at, self)
93 }
94}
95
96/// Future for the [`with_timeout`] and [`with_deadline`] functions.
97#[must_use = "futures do nothing unless you `.await` or poll them"]
98#[derive(Debug)]
99#[cfg_attr(feature = "defmt", derive(defmt::Format))]
100pub struct TimeoutFuture<F> {
101 timer: Timer,
102 fut: F,
103}
104
105impl<F: Unpin> Unpin for TimeoutFuture<F> {}
106
107impl<F: Future> Future for TimeoutFuture<F> {
108 type Output = Result<F::Output, TimeoutError>;
109
110 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
111 let this = unsafe { self.get_unchecked_mut() };
112 let fut = unsafe { Pin::new_unchecked(&mut this.fut) };
113 let timer = unsafe { Pin::new_unchecked(&mut this.timer) };
114 if let Poll::Ready(x) = fut.poll(cx) {
115 return Poll::Ready(Ok(x));
116 }
117 if let Poll::Ready(_) = timer.poll(cx) {
118 return Poll::Ready(Err(TimeoutError));
119 }
120 Poll::Pending
121 }
122}
123
124/// A future that completes at a specified [Instant](struct.Instant.html).
125#[must_use = "futures do nothing unless you `.await` or poll them"]
126#[derive(Debug)]
127#[cfg_attr(feature = "defmt", derive(defmt::Format))]
128pub struct Timer {
129 expires_at: Instant,
130 yielded_once: bool,
131}
132
133impl Timer {
134 /// Expire at specified [Instant](struct.Instant.html)
135 /// Will expire immediately if the Instant is in the past.
136 pub fn at(expires_at: Instant) -> Self {
137 Self {
138 expires_at,
139 yielded_once: false,
140 }
141 }
142
143 /// Expire after specified [Duration](struct.Duration.html).
144 /// This can be used as a `sleep` abstraction.
145 ///
146 /// ## Panics
147 ///
148 /// Panics if the computed instant overflows.
149 /// Avoid panics with [`Timer::try_after()`].
150 ///
151 /// ## Example
152 ///
153 /// ``` no_run
154 /// use embassy_time::{Duration, Timer};
155 ///
156 /// #[embassy_executor::task]
157 /// async fn demo_sleep_seconds() {
158 /// // suspend this task for one second.
159 /// Timer::after(Duration::from_secs(1)).await;
160 /// }
161 /// ```
162 pub fn after(duration: impl Into<Duration>) -> Self {
163 let expires_at = Instant::now() + duration.into();
164 Self::at(expires_at)
165 }
166
167 /// Try to expire after specified [Duration](struct.Duration.html).
168 /// This can be used as a `sleep` abstraction.
169 ///
170 /// This is a panic-free [`Timer::after()`].
171 pub fn try_after(duration: impl Into<Duration>) -> Option<Self> {
172 let expires_at = Instant::now().checked_add(duration.into())?;
173 Some(Self::at(expires_at))
174 }
175
176 /// Expire after the specified number of ticks.
177 ///
178 /// This method is a convenience wrapper for calling `Timer::after(Duration::from_ticks())`.
179 /// For more details, refer to [`Timer::after()`] and [`Duration::from_ticks()`].
180 ///
181 /// ## Panics
182 ///
183 /// Panics if the computed instant overflows.
184 /// Avoid panics with [`Timer::try_after_ticks()`].
185 #[inline]
186 pub fn after_ticks(ticks: u64) -> Self {
187 Self::after(Duration::from_ticks(ticks))
188 }
189
190 /// Try to expire after the specified number of ticks.
191 ///
192 /// This method is a convenience wrapper for calling `Timer::try_after(Duration::from_ticks())`.
193 /// For more details, refer to [`Timer::try_after()`] and [`Duration::from_ticks()`].
194 ///
195 /// This is a panic-free [`Timer::after_ticks()`].
196 #[inline]
197 pub fn try_after_ticks(ticks: u64) -> Option<Self> {
198 Self::try_after(Duration::from_ticks(ticks))
199 }
200
201 /// Expire after the specified number of nanoseconds.
202 ///
203 /// This method is a convenience wrapper for calling `Timer::after(Duration::from_nanos())`.
204 /// For more details, refer to [`Timer::after()`] and [`Duration::from_nanos()`].
205 ///
206 /// ## Panics
207 ///
208 /// Panics if the computed instant overflows.
209 /// Avoid panics with [`Timer::try_after_nanos()`].
210 #[inline]
211 pub fn after_nanos(nanos: u64) -> Self {
212 Self::after(Duration::from_nanos(nanos))
213 }
214
215 /// Try to expire after the specified number of nanoseconds.
216 ///
217 /// This method is a convenience wrapper for calling `Timer::try_after(Duration::from_ticks())`.
218 /// For more details, refer to [`Timer::try_after()`] and [`Duration::from_nanos()`].
219 ///
220 /// This is a panic-free [`Timer::after_nanos()`].
221 #[inline]
222 pub fn try_after_nanos(nanos: u64) -> Option<Self> {
223 Self::try_after(Duration::from_nanos(nanos))
224 }
225
226 /// Expire after the specified number of microseconds.
227 ///
228 /// This method is a convenience wrapper for calling `Timer::after(Duration::from_micros())`.
229 /// For more details, refer to [`Timer::after()`] and [`Duration::from_micros()`].
230 ///
231 /// ## Panics
232 ///
233 /// Panics if the computed instant overflows.
234 /// Avoid panics with [`Timer::try_after_nanos()`].
235 #[inline]
236 pub fn after_micros(micros: u64) -> Self {
237 Self::after(Duration::from_micros(micros))
238 }
239
240 /// Try to expire after the specified number of microseconds.
241 ///
242 /// This method is a convenience wrapper for calling `Timer::try_after(Duration::from_micros())`.
243 /// For more details, refer to [`Timer::try_after()`] and [`Duration::from_micros()`].
244 ///
245 /// This is a panic-free [`Timer::after_micros()`].
246 #[inline]
247 pub fn try_after_micros(micros: u64) -> Option<Self> {
248 Self::try_after(Duration::from_micros(micros))
249 }
250
251 /// Expire after the specified number of milliseconds.
252 ///
253 /// This method is a convenience wrapper for calling `Timer::after(Duration::from_millis())`.
254 /// For more details, refer to [`Timer::after`] and [`Duration::from_millis()`].
255 ///
256 /// ## Panics
257 ///
258 /// Panics if the computed instant overflows.
259 /// Avoid panics with [`Timer::try_after_millis()`].
260 #[inline]
261 pub fn after_millis(millis: u64) -> Self {
262 Self::after(Duration::from_millis(millis))
263 }
264
265 /// Try to expire after the specified number of milliseconds.
266 ///
267 /// This method is a convenience wrapper for calling `Timer::try_after(Duration::from_millis())`.
268 /// For more details, refer to [`Timer::try_after`] and [`Duration::from_millis()`].
269 ///
270 /// This is a panic-free [`Timer::after_millis()`].
271 #[inline]
272 pub fn try_after_millis(millis: u64) -> Option<Self> {
273 Self::try_after(Duration::from_millis(millis))
274 }
275
276 /// Expire after the specified number of seconds.
277 ///
278 /// This method is a convenience wrapper for calling `Timer::after(Duration::from_secs())`.
279 /// For more details, refer to [`Timer::after`] and [`Duration::from_secs()`].
280 ///
281 /// ## Panics
282 ///
283 /// Panics if the computed instant overflows.
284 /// Avoid panics with [`Timer::try_after_secs()`].
285 #[inline]
286 pub fn after_secs(secs: u64) -> Self {
287 Self::after(Duration::from_secs(secs))
288 }
289
290 /// Try to expire after the specified number of seconds.
291 ///
292 /// This method is a convenience wrapper for calling `Timer::try_after(Duration::from_secs())`.
293 /// For more details, refer to [`Timer::try_after`] and [`Duration::from_secs()`].
294 ///
295 /// This is a panic-free [`Timer::after_secs()`].
296 #[inline]
297 pub fn try_after_secs(secs: u64) -> Option<Self> {
298 Self::try_after(Duration::from_secs(secs))
299 }
300}
301
302impl Unpin for Timer {}
303
304impl Future for Timer {
305 type Output = ();
306 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
307 if self.yielded_once && self.expires_at <= Instant::now() {
308 Poll::Ready(())
309 } else {
310 embassy_time_driver::schedule_wake(self.expires_at.as_ticks(), cx.waker());
311 self.yielded_once = true;
312 Poll::Pending
313 }
314 }
315}
316
317/// Asynchronous stream that yields every Duration, indefinitely.
318///
319/// This stream will tick at uniform intervals, even if blocking work is performed between ticks.
320///
321/// For instance, consider the following code fragment.
322/// ``` no_run
323/// use embassy_time::{Duration, Timer};
324/// # fn foo() {}
325///
326/// #[embassy_executor::task]
327/// async fn ticker_example_0() {
328/// loop {
329/// foo();
330/// Timer::after(Duration::from_secs(1)).await;
331/// }
332/// }
333/// ```
334///
335/// This fragment will not call `foo` every second.
336/// Instead, it will call it every second + the time it took to previously call `foo`.
337///
338/// Example using ticker, which will consistently call `foo` once a second.
339///
340/// ``` no_run
341/// use embassy_time::{Duration, Ticker};
342/// # fn foo(){}
343///
344/// #[embassy_executor::task]
345/// async fn ticker_example_1() {
346/// let mut ticker = Ticker::every(Duration::from_secs(1));
347/// loop {
348/// foo();
349/// ticker.next().await;
350/// }
351/// }
352/// ```
353///
354/// ## Cancel safety
355/// It is safe to cancel waiting for the next tick,
356/// meaning no tick is lost if the Future is dropped.
357#[derive(Debug)]
358#[cfg_attr(feature = "defmt", derive(defmt::Format))]
359pub struct Ticker {
360 expires_at: Instant,
361 duration: Duration,
362}
363
364impl Ticker {
365 /// Creates a new ticker that ticks at the specified duration interval.
366 ///
367 /// ## Panics
368 ///
369 /// Panics if the computed instant overflows.
370 /// Avoid panics with [`Ticker::try_every()`].
371 pub fn every(duration: impl Into<Duration>) -> Self {
372 let duration = duration.into();
373 let expires_at = Instant::now() + duration;
374 Self { expires_at, duration }
375 }
376
377 /// Tries to create a new ticker that ticks at the specified duration interval.
378 ///
379 /// This is a panic-free [`Ticker::every()`].
380 pub fn try_every(duration: impl Into<Duration>) -> Option<Self> {
381 let duration = duration.into();
382 let expires_at = Instant::now().checked_add(duration)?;
383 Some(Self { expires_at, duration })
384 }
385
386 /// Creates a new ticker that ticks immediately then at the specified duration interval.
387 ///
388 /// This is equivalent to `Ticker::every()` plus `reset_to_now()`.
389 pub fn now_and_every(duration: impl Into<Duration>) -> Self {
390 let duration = duration.into();
391 let expires_at = Instant::now();
392 Self { expires_at, duration }
393 }
394
395 /// Resets the ticker back to its original state.
396 /// This causes the ticker to go back to zero, even if the current tick isn't over yet.
397 ///
398 /// ## Panics
399 ///
400 /// Panics if the computed instant overflows.
401 /// Avoid panics with [`Ticker::checked_reset()`].
402 pub fn reset(&mut self) {
403 self.expires_at = Instant::now() + self.duration;
404 }
405
406 /// Checked resets the ticker back to its original state.
407 /// This causes the ticker to go back to zero, even if the current tick isn't over yet.
408 ///
409 /// This is a panic-free [`Ticker::reset()`].
410 pub fn checked_reset(&mut self) -> Option<()> {
411 self.expires_at = Instant::now().checked_add(self.duration)?;
412 Some(())
413 }
414
415 /// Reset the ticker at the deadline.
416 /// If the deadline is in the past, the ticker will fire before the next scheduled tick.
417 ///
418 /// ## Panics
419 ///
420 /// Panics if the computed instant overflows.
421 /// Avoid panics with [`Ticker::checked_reset_at()`].
422 pub fn reset_at(&mut self, deadline: Instant) {
423 self.expires_at = deadline + self.duration;
424 }
425
426 /// Checked reset the ticker at the deadline.
427 /// If the deadline is in the past, the ticker will fire before the next scheduled tick.
428 ///
429 /// This is a panic-free [`Ticker::reset_at()`].
430 pub fn checked_reset_at(&mut self, deadline: Instant) -> Option<()> {
431 self.expires_at = deadline.checked_add(self.duration)?;
432 Some(())
433 }
434
435 /// Resets the ticker, after the specified duration has passed.
436 /// If the specified duration is zero, the next tick will be after the duration of the ticker.
437 ///
438 /// ## Panics
439 ///
440 /// Panics if the computed instant overflows.
441 /// Avoid panics with [`Ticker::checked_reset_after()`].
442 pub fn reset_after(&mut self, after: impl Into<Duration>) {
443 let after = after.into();
444 self.expires_at = Instant::now() + after + self.duration;
445 }
446
447 /// Checked resets the ticker, after the specified duration has passed.
448 /// If the specified duration is zero, the next tick will be after the duration of the ticker.
449 ///
450 /// This is a panic-free [`Ticker::reset_after()`].
451 pub fn checked_reset_after(&mut self, after: impl Into<Duration>) -> Option<()> {
452 let after = after.into();
453 self.expires_at = Instant::now().checked_add(after)?.checked_add(self.duration)?;
454 Some(())
455 }
456
457 /// Resets the ticker to fire immediately.
458 pub fn reset_to_now(&mut self) {
459 self.expires_at = Instant::now();
460 }
461
462 /// Waits for the next tick.
463 ///
464 /// ## Panics
465 ///
466 /// Panics if the next computed instant overflows.
467 ///
468 /// ## Cancel safety
469 /// The produced Future is cancel safe, meaning no tick is lost if the Future is dropped.
470 pub fn next(&mut self) -> impl Future<Output = ()> + Send + Sync + '_ {
471 poll_fn(|cx| {
472 if self.expires_at <= Instant::now() {
473 let dur = self.duration;
474 self.expires_at += dur;
475 Poll::Ready(())
476 } else {
477 embassy_time_driver::schedule_wake(self.expires_at.as_ticks(), cx.waker());
478 Poll::Pending
479 }
480 })
481 }
482}
483
484impl Unpin for Ticker {}
485
486impl Stream for Ticker {
487 type Item = ();
488 /// Attempt to pull the next tick from this [`Stream`].
489 ///
490 /// * Returns `Poll::Pending` if the instant is in the future.
491 /// * Returns `Poll::Ready(Some(()))` if the instant has been reached, and computes the next instant.
492 ///
493 /// ## Panics
494 ///
495 /// Panics if the computed instant overflows.
496 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
497 if self.expires_at <= Instant::now() {
498 let dur = self.duration;
499 self.expires_at += dur;
500 Poll::Ready(Some(()))
501 } else {
502 embassy_time_driver::schedule_wake(self.expires_at.as_ticks(), cx.waker());
503 Poll::Pending
504 }
505 }
506}
507
508impl FusedStream for Ticker {
509 fn is_terminated(&self) -> bool {
510 // `Ticker` keeps yielding values until dropped, it never terminates.
511 false
512 }
513}
514
515impl core::fmt::Display for TimeoutError {
516 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
517 f.write_str("TimeoutError")
518 }
519}
520impl core::error::Error for TimeoutError {}
521
522#[cfg(all(test, feature = "std"))]
523mod test {
524 use super::*;
525
526 #[test]
527 #[should_panic(expected = "overflow")]
528 #[cfg(panic = "unwind")]
529 fn with_timeout_panics() {
530 while Instant::now() == Instant::MIN {} // with non-0 tick
531 let _ = with_timeout(Duration::MAX, async {}); // PANIC
532 }
533
534 #[test]
535 fn try_with_timeout_none() {
536 while Instant::now() == Instant::MIN {} // with non-0 tick
537 assert!(try_with_timeout(Duration::MAX, async {}).is_none());
538 }
539
540 #[test]
541 #[should_panic(expected = "overflow")]
542 #[cfg(panic = "unwind")]
543 fn timer_after_panics() {
544 while Instant::now() == Instant::MIN {} // with non-0 tick
545 let _ = Timer::after(Duration::MAX); // PANIC
546 }
547
548 #[test]
549 fn timer_try_after_none() {
550 while Instant::now() == Instant::MIN {} // with non-0 tick
551 assert!(Timer::try_after(Duration::MAX).is_none());
552 }
553
554 #[test]
555 #[should_panic(expected = "overflow")]
556 #[cfg(panic = "unwind")]
557 fn ticker_every_panics() {
558 while Instant::now() == Instant::MIN {} // with non-0 tick
559 let _ = Ticker::every(Duration::MAX); // PANIC
560 }
561
562 #[test]
563 fn ticker_try_every_none() {
564 while Instant::now() == Instant::MIN {} // with non-0 tick
565 assert!(Ticker::try_every(Duration::MAX).is_none());
566 }
567
568 #[test]
569 #[should_panic(expected = "overflow")]
570 #[cfg(panic = "unwind")]
571 fn ticker_reset_panics() {
572 let mut ticker = Ticker {
573 expires_at: Instant::MAX,
574 duration: Duration::MAX,
575 };
576 while Instant::now() == Instant::MIN {} // with non-0 tick
577 ticker.reset(); // PANIC
578 }
579
580 #[test]
581 fn ticker_checked_reset_none() {
582 let mut ticker = Ticker {
583 expires_at: Instant::MAX,
584 duration: Duration::MAX,
585 };
586 while Instant::now() == Instant::MIN {} // with non-0 tick
587 assert!(ticker.checked_reset().is_none());
588 }
589
590 #[test]
591 #[should_panic(expected = "overflow")]
592 #[cfg(panic = "unwind")]
593 fn ticker_reset_at_panics() {
594 let mut ticker = Ticker {
595 expires_at: Instant::MAX,
596 duration: Duration::MAX,
597 };
598 ticker.reset_at(Instant::MAX); // PANIC
599 }
600
601 #[test]
602 fn ticker_checked_reset_at_none() {
603 let mut ticker = Ticker {
604 expires_at: Instant::MAX,
605 duration: Duration::MAX,
606 };
607 assert!(ticker.checked_reset_at(Instant::MAX).is_none());
608 }
609
610 #[test]
611 #[should_panic(expected = "overflow")]
612 #[cfg(panic = "unwind")]
613 fn ticker_reset_after_panics() {
614 let mut ticker = Ticker {
615 expires_at: Instant::MAX,
616 duration: Duration::MAX,
617 };
618 while Instant::now() == Instant::MIN {} // with non-0 tick
619 ticker.reset_after(Duration::MAX); // PANIC
620 }
621
622 #[test]
623 fn ticker_checked_reset_after_none() {
624 let mut ticker = Ticker {
625 expires_at: Instant::MAX,
626 duration: Duration::MAX,
627 };
628 while Instant::now() == Instant::MIN {} // with non-0 tick
629 assert!(ticker.checked_reset_after(Duration::MAX).is_none());
630 }
631}