ntex_util/time/mod.rs
1//! Utilities for tracking time.
2//!
3//! Use [`sleep`], [`deadline`] or [`interval`] for asynchronous waits. To run a
4//! short synchronous callback without polling a timer future, retain a
5//! [`CallbackTimer`].
6#![allow(
7 clippy::cast_possible_truncation,
8 clippy::cast_sign_loss,
9 clippy::cast_possible_wrap
10)]
11use std::{cmp, future::Future, future::poll_fn, pin::Pin, task, task::Poll, time::Instant};
12
13use ntex_rt::time::CallbackHandle;
14
15mod types;
16
17pub use self::types::{Millis, Seconds};
18pub use ntex_rt::time::{TimerHandle, system_time};
19
20/// Returns the start of the current runtime turn, see [`ntex_rt::now()`].
21///
22/// Tasks polled in the same turn observe the same instant on neon and compio,
23/// on tokio this is [`Instant::now()`].
24#[inline]
25pub fn now() -> Instant {
26 ntex_rt::now()
27}
28
29/// A reusable, local one-shot callback timer.
30///
31/// Each construction or reset arms one invocation of the retained callback.
32/// The callback may capture `Rc` state; this handle is neither `Send` nor `Sync`
33/// and cannot be cloned. Keep the handle alive until the callback should run.
34/// Dropping it cancels pending delivery, including an expired callback that has
35/// not started, and releases its captures. An active invocation retains its
36/// captures until it finishes.
37///
38/// Expiration and cancellation retain the callback for reuse. The callback
39/// implements `Fn`, so use interior mutability for state that changes between
40/// invocations.
41///
42/// Callbacks run outside wheel access and may create, reset, cancel or drop
43/// timers, including themselves. They must be short, synchronous and
44/// non-blocking. Callbacks due on the same tick have no guaranteed order.
45///
46/// Callback panics propagate through the runtime. They may stop the shared
47/// driver and disarm other timers; remaining callbacks need not be delivered.
48/// Runtime shutdown suppresses pending delivery. A surviving handle retains
49/// its callback and can be explicitly reset in a new runtime on the same thread.
50/// Starting a new runtime does not automatically rearm the handle.
51///
52/// # Examples
53///
54/// Retain local state across invocations, cancel an arm, then reuse the timer:
55///
56/// ```
57/// use std::{cell::Cell, rc::Rc};
58/// use ntex::time::{CallbackTimer, Millis, sleep};
59///
60/// #[ntex::main]
61/// async fn main() {
62/// let calls = Rc::new(Cell::new(0));
63/// let count = calls.clone();
64/// let timer = CallbackTimer::new(Millis::ZERO, move || {
65/// count.set(count.get() + 1);
66/// });
67/// assert_eq!(calls.get(), 0); // Zero duration never invokes inline.
68/// sleep(Millis(50)).await;
69/// assert!(timer.is_elapsed());
70/// assert_eq!(calls.get(), 1);
71///
72/// timer.reset(Millis(1_000));
73/// timer.cancel();
74/// assert!(timer.is_elapsed());
75///
76/// timer.reset(Millis::ZERO);
77/// sleep(Millis(50)).await;
78/// assert_eq!(calls.get(), 2);
79/// }
80/// ```
81#[derive(Debug)]
82pub struct CallbackTimer(CallbackHandle);
83
84impl CallbackTimer {
85 /// Arms a callback after `duration`, using the wheel's rounding and limits.
86 ///
87 /// The base granularity is approximately 16 ms by default, see
88 /// [`Builder::timer_resolution`](ntex_rt::Builder::timer_resolution);
89 /// longer delays use coarser rounding, and delays beyond the wheel's
90 /// capacity (about 24 days at 16 ms) are clamped. Callback delivery may be
91 /// delayed further while the runtime is busy.
92 ///
93 /// A zero duration waits for a subsequent timer tick, as with [`Sleep`];
94 /// the callback is never invoked inline.
95 pub fn new(duration: Millis, callback: impl Fn() + 'static) -> Self {
96 CallbackTimer(CallbackHandle::new(u64::from(duration.0), callback))
97 }
98
99 /// Arms another invocation, invalidating any previous pending delivery.
100 ///
101 /// This also suppresses an expired invocation that has been queued but has
102 /// not started. It can be called before or after expiration or cancellation.
103 ///
104 /// A zero duration waits for a subsequent tick. Resetting from within the
105 /// callback arms a new invocation, which survives completion of the old one.
106 pub fn reset(&self, duration: Millis) {
107 self.0.reset(u64::from(duration.0));
108 }
109
110 /// Disarms the timer and suppresses pending delivery, retaining the callback.
111 ///
112 /// This also suppresses an expired invocation that has not started. Calling
113 /// this method on an already disarmed timer is harmless.
114 ///
115 /// An invocation that has already started cannot be interrupted.
116 pub fn cancel(&self) {
117 self.0.cancel();
118 }
119
120 /// Returns `true` when disarmed, including after cancellation or shutdown.
121 ///
122 /// Expiration marks the timer elapsed before callback delivery. This query
123 /// does not indicate whether the callback has run.
124 pub fn is_elapsed(&self) -> bool {
125 self.0.is_elapsed()
126 }
127}
128
129/// Waits until `dur` has elapsed.
130///
131/// No work is performed while awaiting the returned [`Sleep`]. Timers have a
132/// granularity of approximately 16 milliseconds by default, see
133/// [`Builder::timer_resolution`](ntex_rt::Builder::timer_resolution), and are
134/// not suitable for high-resolution timing. A zero duration still waits for at
135/// least one timer tick.
136#[inline]
137pub fn sleep<T: Into<Millis>>(dur: T) -> Sleep {
138 Sleep::new(dur.into())
139}
140
141/// Waits until `dur` has elapsed.
142///
143/// Unlike [`sleep`], a zero-duration deadline never completes.
144#[inline]
145pub fn deadline<T: Into<Millis>>(dur: T) -> Deadline {
146 Deadline::new(dur.into())
147}
148
149/// Creates an [`Interval`] that ticks every `period`.
150///
151/// The first tick completes immediately, and each later tick completes
152/// `period` after the previous one was observed. An interval will tick
153/// indefinitely. At any time, the [`Interval`] value can be dropped. This
154/// cancels the interval.
155#[inline]
156pub fn interval<T: Into<Millis>>(period: T) -> Interval {
157 Interval::new(period.into())
158}
159
160/// Requires a future to complete before `dur` has elapsed.
161///
162/// If the future completes before the duration has elapsed, then the completed
163/// value is returned. Otherwise, an error is returned and the future is
164/// canceled. A zero duration still represents an active timeout of at least
165/// one timer tick; use [`timeout_checked`] to disable the timeout with zero. If
166/// the future and timer are both ready during the same poll, the future wins.
167#[inline]
168pub fn timeout<T, U>(dur: U, future: T) -> Timeout<T>
169where
170 T: Future,
171 U: Into<Millis>,
172{
173 Timeout::new_with_delay(future, Sleep::new(dur.into()))
174}
175
176/// Requires a future to complete before `dur` has elapsed.
177///
178/// If the future completes before the duration has elapsed, then the completed
179/// value is returned. Otherwise, an error is returned and the future is
180/// canceled. A zero duration disables the timeout.
181#[inline]
182pub fn timeout_checked<T, U>(dur: U, future: T) -> TimeoutChecked<T>
183where
184 T: Future,
185 U: Into<Millis>,
186{
187 TimeoutChecked::new_with_delay(future, dur.into())
188}
189
190/// Future returned by [`sleep`].
191///
192/// # Examples
193///
194/// Wait 100ms and print "100 ms have elapsed".
195///
196/// ```
197/// use ntex::time::{sleep, Millis};
198///
199/// #[ntex::main]
200/// async fn main() {
201/// sleep(Millis(100)).await;
202/// println!("100 ms have elapsed");
203/// }
204/// ```
205///
206/// # Single waiter
207///
208/// A timer stores one waker. [`wait`](Self::wait) and
209/// [`poll_elapsed`](Self::poll_elapsed) take `&self`, but only the task that
210/// polled most recently is woken when the timer elapses. Wait from one task at
211/// a time; an earlier concurrent waiter may stay pending after the deadline.
212/// The same applies to [`Deadline`] and [`TimerHandle`].
213#[derive(Debug)]
214#[must_use = "futures do nothing unless you `.await` or poll them"]
215pub struct Sleep {
216 // The link between the `Sleep` instance and the timer that drives it.
217 hnd: TimerHandle,
218}
219
220impl Sleep {
221 /// Creates a new sleep future.
222 ///
223 /// A zero duration is rounded up to 1 ms.
224 #[inline]
225 pub fn new(duration: Millis) -> Sleep {
226 Sleep {
227 hnd: TimerHandle::new(u64::from(cmp::max(duration.0, 1))),
228 }
229 }
230
231 /// Returns `true` if `Sleep` has elapsed.
232 #[inline]
233 pub fn is_elapsed(&self) -> bool {
234 self.hnd.is_elapsed()
235 }
236
237 /// Completes the timer immediately.
238 #[inline]
239 pub fn elapse(&self) {
240 self.hnd.elapse();
241 }
242
243 /// Resets the `Sleep` instance to a new deadline.
244 ///
245 /// Calling this function allows changing the instant at which the `Sleep`
246 /// future completes without having to create new associated state.
247 ///
248 /// This function can be called both before and after the future has
249 /// completed. A zero duration is rounded up to 1 ms.
250 pub fn reset<T: Into<Millis>>(&self, millis: T) {
251 self.hnd.reset(u64::from(cmp::max(millis.into().0, 1)));
252 }
253
254 #[inline]
255 /// Waits until this timer has elapsed.
256 ///
257 /// Only one task may wait at a time; see [single waiter](Self#single-waiter).
258 pub async fn wait(&self) {
259 poll_fn(|cx| self.hnd.poll_elapsed(cx)).await;
260 }
261
262 #[inline]
263 /// Polls until this timer has elapsed.
264 ///
265 /// A pending poll replaces the previously registered waker; see
266 /// [single waiter](Self#single-waiter).
267 pub fn poll_elapsed(&self, cx: &mut task::Context<'_>) -> Poll<()> {
268 self.hnd.poll_elapsed(cx)
269 }
270}
271
272impl Future for Sleep {
273 type Output = ();
274
275 fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
276 self.hnd.poll_elapsed(cx)
277 }
278}
279
280/// Future returned by [`deadline`].
281///
282/// # Examples
283///
284/// Wait 100ms and print "100 ms have elapsed".
285///
286/// ```
287/// use ntex::time::{deadline, Millis};
288///
289/// #[ntex::main]
290/// async fn main() {
291/// deadline(Millis(100)).await;
292/// println!("100 ms have elapsed");
293/// }
294/// ```
295#[derive(Debug)]
296#[must_use = "futures do nothing unless you `.await` or poll them"]
297pub struct Deadline {
298 hnd: Option<TimerHandle>,
299}
300
301impl Deadline {
302 /// Creates a new deadline future.
303 ///
304 /// A zero duration creates a deadline that never completes.
305 #[inline]
306 pub fn new(duration: Millis) -> Deadline {
307 if duration.0 != 0 {
308 Deadline {
309 hnd: Some(TimerHandle::new(u64::from(duration.0))),
310 }
311 } else {
312 Deadline { hnd: None }
313 }
314 }
315
316 #[inline]
317 /// Waits until this deadline has elapsed.
318 ///
319 /// Only one task may wait at a time; see
320 /// [single waiter](Sleep#single-waiter).
321 pub async fn wait(&self) {
322 poll_fn(|cx| self.poll_elapsed(cx)).await;
323 }
324
325 /// Resets the `Deadline` instance to a new deadline.
326 ///
327 /// Calling this function allows changing the instant at which the `Deadline`
328 /// future completes without having to create new associated state.
329 ///
330 /// This function can be called both before and after the future has
331 /// completed.
332 pub fn reset<T: Into<Millis>>(&mut self, millis: T) {
333 let millis = millis.into();
334 if millis.0 != 0 {
335 if let Some(ref mut hnd) = self.hnd {
336 hnd.reset(u64::from(millis.0));
337 } else {
338 self.hnd = Some(TimerHandle::new(u64::from(millis.0)));
339 }
340 } else {
341 let _ = self.hnd.take();
342 }
343 }
344
345 /// Returns `true` if `Deadline` has elapsed.
346 ///
347 /// This agrees with polling: it returns `true` exactly when polling the
348 /// deadline completes. A disabled zero-duration deadline never elapses,
349 /// so it returns `false`.
350 #[inline]
351 pub fn is_elapsed(&self) -> bool {
352 self.hnd.as_ref().is_some_and(TimerHandle::is_elapsed)
353 }
354
355 #[inline]
356 /// Polls until this deadline has elapsed.
357 ///
358 /// A zero-duration deadline remains pending until it is reset. A pending
359 /// poll replaces the previously registered waker; see
360 /// [single waiter](Sleep#single-waiter).
361 pub fn poll_elapsed(&self, cx: &mut task::Context<'_>) -> Poll<()> {
362 self.hnd
363 .as_ref()
364 .map_or(Poll::Pending, |t| t.poll_elapsed(cx))
365 }
366}
367
368impl Future for Deadline {
369 type Output = ();
370
371 fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
372 self.poll_elapsed(cx)
373 }
374}
375
376pin_project_lite::pin_project! {
377 /// Future returned by [`timeout`](timeout).
378 #[must_use = "futures do nothing unless you `.await` or poll them"]
379 #[derive(Debug)]
380 pub struct Timeout<T> {
381 #[pin]
382 value: T,
383 delay: Sleep,
384 }
385}
386
387impl<T> Timeout<T> {
388 pub(crate) fn new_with_delay(value: T, delay: Sleep) -> Timeout<T> {
389 Timeout { value, delay }
390 }
391}
392
393impl<T> Future for Timeout<T>
394where
395 T: Future,
396{
397 type Output = Result<T::Output, ()>;
398
399 fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
400 let this = self.project();
401
402 // First, try polling the future
403 if let Poll::Ready(v) = this.value.poll(cx) {
404 return Poll::Ready(Ok(v));
405 }
406
407 // Now check the timer
408 match this.delay.poll_elapsed(cx) {
409 Poll::Ready(()) => Poll::Ready(Err(())),
410 Poll::Pending => Poll::Pending,
411 }
412 }
413}
414
415pin_project_lite::pin_project! {
416 /// Future returned by [`timeout_checked`](timeout_checked).
417 #[must_use = "futures do nothing unless you `.await` or poll them"]
418 pub struct TimeoutChecked<T> {
419 #[pin]
420 state: TimeoutCheckedState<T>,
421 }
422}
423
424pin_project_lite::pin_project! {
425 #[project = TimeoutCheckedStateProject]
426 enum TimeoutCheckedState<T> {
427 Timeout{ #[pin] fut: Timeout<T> },
428 NoTimeout{ #[pin] fut: T },
429 }
430}
431
432impl<T> TimeoutChecked<T> {
433 pub(crate) fn new_with_delay(value: T, delay: Millis) -> TimeoutChecked<T> {
434 if delay.is_zero() {
435 TimeoutChecked {
436 state: TimeoutCheckedState::NoTimeout { fut: value },
437 }
438 } else {
439 TimeoutChecked {
440 state: TimeoutCheckedState::Timeout {
441 fut: Timeout::new_with_delay(value, sleep(delay)),
442 },
443 }
444 }
445 }
446}
447
448impl<T> Future for TimeoutChecked<T>
449where
450 T: Future,
451{
452 type Output = Result<T::Output, ()>;
453
454 fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
455 match self.project().state.as_mut().project() {
456 TimeoutCheckedStateProject::Timeout { fut } => fut.poll(cx),
457 TimeoutCheckedStateProject::NoTimeout { fut } => fut.poll(cx).map(Result::Ok),
458 }
459 }
460}
461
462/// An interval returned by [`interval`].
463///
464/// This type allows you to wait on a sequence of instants with a certain
465/// duration between each instant.
466#[must_use = "futures do nothing unless you `.await` or poll them"]
467#[derive(Debug)]
468pub struct Interval {
469 hnd: TimerHandle,
470 period: u32,
471}
472
473impl Interval {
474 /// Creates an interval with the specified period.
475 ///
476 /// The first tick completes immediately. A zero period is rounded up to
477 /// 1 ms.
478 #[inline]
479 pub fn new(period: Millis) -> Interval {
480 Interval {
481 hnd: TimerHandle::new(0),
482 period: cmp::max(period.0, 1),
483 }
484 }
485
486 #[inline]
487 /// Waits for the next interval tick.
488 pub async fn tick(&self) {
489 poll_fn(|cx| self.poll_tick(cx)).await;
490 }
491
492 #[inline]
493 /// Polls for the next interval tick.
494 pub fn poll_tick(&self, cx: &mut task::Context<'_>) -> Poll<()> {
495 if self.hnd.poll_elapsed(cx).is_ready() {
496 self.hnd.reset(u64::from(self.period));
497 Poll::Ready(())
498 } else {
499 Poll::Pending
500 }
501 }
502}
503
504impl crate::Stream for Interval {
505 type Item = ();
506
507 #[inline]
508 fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
509 self.poll_tick(cx).map(|()| Some(()))
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use futures_util::StreamExt;
516 use std::{future::poll_fn, rc::Rc, time};
517
518 use super::*;
519 use crate::future::lazy;
520
521 /// STATEMENT: Cached `now()` is not in the future and stays close to the current instant.
522 ///
523 /// HOW:
524 /// - Sleep, then compare `now()` with `Instant::now`.
525 /// - Verify the cached value is no later and less than 50 milliseconds behind.
526 #[ntex::test]
527 async fn now_is_current() {
528 sleep(Millis(25)).await;
529
530 let now = now();
531 let cur = time::Instant::now();
532 assert!(cur >= now);
533 assert!(cur - now < time::Duration::from_millis(50));
534 }
535
536 /// STATEMENT: Cached `now()` advances across an awaited sleep.
537 ///
538 /// HOW:
539 /// - Read `now()` before and after a 25-millisecond sleep.
540 /// - Verify the second value advances by at least that duration.
541 #[ntex::test]
542 async fn now_updates_after_sleep() {
543 sleep(Millis(50)).await;
544
545 let first_time = now();
546
547 sleep(Millis(25)).await;
548
549 let second_time = now();
550 assert!(second_time - first_time >= time::Duration::from_millis(25));
551 }
552
553 /// STATEMENT: Back-to-back system-time reads share the cached value.
554 ///
555 /// HOW:
556 /// - Let the runtime advance, then compare two consecutive `system_time()` calls.
557 #[ntex::test]
558 async fn system_time_service_time_does_not_immediately_change() {
559 sleep(Seconds(1)).await;
560
561 assert_eq!(system_time(), system_time());
562 }
563
564 /// STATEMENT: Cached system time advances after sleeping beyond its refresh interval.
565 ///
566 /// HOW:
567 /// - Read system time around a 600-millisecond sleep.
568 /// - Compare epoch-relative durations and require at least that much advancement.
569 #[ntex::test]
570 async fn system_time_service_time_updates_after_resolution_interval() {
571 sleep(Millis(100)).await;
572
573 let wait_time = 600;
574
575 let first_time = system_time()
576 .duration_since(time::SystemTime::UNIX_EPOCH)
577 .unwrap();
578
579 sleep(Millis(wait_time)).await;
580
581 let second_time = system_time()
582 .duration_since(time::SystemTime::UNIX_EPOCH)
583 .unwrap();
584
585 assert!(
586 second_time.checked_sub(first_time).unwrap()
587 >= time::Duration::from_millis(u64::from(wait_time))
588 );
589 }
590
591 /// STATEMENT: Zero sleeps round up, while explicitly elapsed timers complete promptly.
592 ///
593 /// HOW:
594 /// - Measure zero, one-millisecond, and reset-to-zero sleeps and check their elapsed state.
595 /// - Await an already-elapsed handle and a manually elapsed shared sleep within short bounds.
596 #[ntex::test]
597 async fn test_sleep_0() {
598 sleep(Seconds(1)).await;
599
600 let first_time = time::Instant::now();
601 sleep(Millis(0)).await;
602 let second_time = time::Instant::now();
603 assert!(second_time - first_time >= time::Duration::from_millis(1));
604
605 let first_time = time::Instant::now();
606 sleep(Millis(1)).await;
607 let second_time = time::Instant::now();
608 assert!(second_time - first_time >= time::Duration::from_millis(1));
609
610 let first_time = time::Instant::now();
611 let fut = sleep(Millis(10000));
612 assert!(!fut.is_elapsed());
613 // a zero delay is rounded up to 1 ms
614 fut.reset(Millis::ZERO);
615 assert!(!fut.is_elapsed());
616 fut.await;
617 let second_time = time::Instant::now();
618 assert!(second_time - first_time >= time::Duration::from_millis(1));
619
620 let fut = sleep(Millis::ZERO);
621 assert!(!fut.is_elapsed());
622 fut.await;
623
624 // `now()` may advance between two calls, measure
625 // with the clock. An elapsed timer completes without waiting for the
626 // timer driver, the bound leaves room for scheduling latency
627 let first_time = time::Instant::now();
628 let fut = Sleep {
629 hnd: TimerHandle::new(0),
630 };
631 assert!(fut.is_elapsed());
632 fut.await;
633 let second_time = time::Instant::now();
634 assert!(second_time - first_time < time::Duration::from_millis(50));
635
636 let first_time = time::Instant::now();
637 let fut = Rc::new(sleep(Millis(10_0000)));
638 let s = fut.clone();
639 ntex::rt::spawn(async move {
640 s.elapse();
641 });
642 poll_fn(|cx| fut.poll_elapsed(cx)).await;
643 assert!(fut.is_elapsed());
644 let second_time = time::Instant::now();
645 assert!(second_time - first_time < time::Duration::from_millis(50));
646 }
647
648 /// STATEMENT: `Deadline::is_elapsed()` agrees with polling for disabled, active, reset and
649 /// expired deadlines.
650 ///
651 /// HOW:
652 /// - Create a zero deadline and assert `is_elapsed()` is `false`, polling stays pending, and
653 /// `timeout()` around it times out.
654 /// - Create a 50 ms deadline and assert neither the predicate nor polling reports elapsed.
655 /// - Await a 1 ms deadline and assert the predicate is `true` and polling is ready.
656 /// - Reset the expired deadline to 50 ms and assert both report not elapsed again, then reset
657 /// it to zero and assert both still report not elapsed after 20 ms.
658 #[ntex::test]
659 async fn test_deadline_is_elapsed_matches_polling() {
660 let dl = deadline(Millis::ZERO);
661 assert!(!dl.is_elapsed());
662 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_pending());
663 assert!(timeout(Millis(20), dl.wait()).await.is_err());
664 assert!(!dl.is_elapsed());
665
666 let dl = deadline(Millis(50));
667 assert!(!dl.is_elapsed());
668 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_pending());
669
670 let mut dl = deadline(Millis(1));
671 dl.wait().await;
672 assert!(dl.is_elapsed());
673 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_ready());
674
675 dl.reset(Millis(50));
676 assert!(!dl.is_elapsed());
677 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_pending());
678
679 dl.reset(Millis::ZERO);
680 sleep(Millis(20)).await;
681 assert!(!dl.is_elapsed());
682 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_pending());
683 }
684
685 /// STATEMENT: Deadlines can be extended, disabled with zero, and re-enabled by reset.
686 ///
687 /// HOW:
688 /// - Measure initial and extended deadlines and time out a zero deadline.
689 /// - Poll disabled and re-enabled deadlines; both stay pending.
690 #[ntex::test]
691 async fn test_deadline() {
692 sleep(Seconds(1)).await;
693
694 let first_time = now();
695 let dl = deadline(Millis(1));
696 dl.await;
697 let second_time = now();
698 assert!(second_time - first_time >= time::Duration::from_millis(1));
699 assert!(timeout(Millis(100), deadline(Millis(0))).await.is_err());
700
701 let mut dl = deadline(Millis(1));
702 dl.reset(Millis::ZERO);
703 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_pending());
704
705 let mut dl = deadline(Millis(1));
706 dl.reset(Millis(100));
707 let first_time = now();
708 dl.await;
709 let second_time = now();
710 assert!(second_time - first_time >= time::Duration::from_millis(100));
711
712 let mut dl = deadline(Millis(0));
713 dl.reset(Millis(1));
714 assert!(lazy(|cx| dl.poll_elapsed(cx)).await.is_pending());
715 }
716
717 /// STATEMENT: A zero-period interval waits between ticks instead of staying immediately ready.
718 ///
719 /// HOW:
720 /// - Consume the first tick, verify the next poll is pending, and await another tick.
721 #[ntex::test]
722 async fn test_interval_zero_period() {
723 let int = interval(Millis::ZERO);
724 int.tick().await;
725
726 // a zero period is rounded up to 1 ms instead of ticking on every poll
727 assert!(lazy(|cx| int.poll_tick(cx)).await.is_pending());
728 int.tick().await;
729 }
730
731 /// STATEMENT: Intervals tick immediately once, then wait for their period through both APIs.
732 ///
733 /// HOW:
734 /// - Measure the first and second explicit ticks of a 250-millisecond interval.
735 /// - Receive another tick through the stream API and check the same timing bounds.
736 #[ntex::test]
737 async fn test_interval() {
738 let mut int = interval(Millis(250));
739
740 // the first tick completes immediately
741 let time = time::Instant::now();
742 int.tick().await;
743 assert!(time.elapsed() < time::Duration::from_millis(50));
744
745 let time = time::Instant::now();
746 int.tick().await;
747 let elapsed = time.elapsed();
748 assert!(
749 elapsed > time::Duration::from_millis(200)
750 && elapsed < time::Duration::from_millis(450),
751 "elapsed: {elapsed:?}"
752 );
753
754 let time = time::Instant::now();
755 int.next().await;
756 let elapsed = time.elapsed();
757 assert!(
758 elapsed > time::Duration::from_millis(200)
759 && elapsed < time::Duration::from_millis(450),
760 "elapsed: {elapsed:?}"
761 );
762 }
763
764 /// STATEMENT: A one-second interval keeps subsequent ticks within the expected timing bounds.
765 ///
766 /// HOW:
767 /// - Consume the immediate tick, then measure two ticks between one and 1.5 seconds each.
768 #[ntex::test]
769 async fn test_interval_one_sec() {
770 let int = interval(Millis::ONE_SEC);
771 int.tick().await;
772
773 for _i in 0..2 {
774 let time = time::Instant::now();
775 int.tick().await;
776 let elapsed = time.elapsed();
777 assert!(
778 elapsed > time::Duration::from_secs(1)
779 && elapsed < time::Duration::from_millis(1500),
780 "elapsed: {elapsed:?}"
781 );
782 }
783 }
784
785 /// STATEMENT: Checked timeouts preserve timely results, expire pending work, and disable at zero.
786 ///
787 /// HOW:
788 /// - Run a shorter sleep under a deadline and a permanently pending future under a short one.
789 /// - Verify a zero timeout allows a delayed future to finish.
790 #[ntex::test]
791 async fn test_timeout_checked() {
792 let result = timeout_checked(Millis(200), sleep(Millis(100))).await;
793 assert!(result.is_ok());
794
795 // a future that never completes, a late timer driver would elapse
796 // a competing sleep in the same pass
797 let result = timeout_checked(Millis(5), std::future::pending::<()>()).await;
798 assert!(result.is_err());
799
800 let result = timeout_checked(Millis(0), sleep(Millis(100))).await;
801 assert!(result.is_ok());
802 }
803
804 /// STATEMENT: Sleep and deadline wait helpers complete except for a disabled zero deadline.
805 ///
806 /// HOW:
807 /// - Await both helpers and check the clock has not moved backward.
808 /// - Wrap a zero deadline's wait in a timeout and verify it never completes first.
809 #[ntex::test]
810 async fn sleep_and_deadline_wait() {
811 let start = now();
812 sleep(Millis(5)).wait().await;
813 deadline(Millis(5)).wait().await;
814 assert!(now() >= start);
815
816 let hnd = Deadline::new(Millis::ZERO);
817 assert!(
818 crate::time::timeout(Millis(20), hnd.wait()).await.is_err(),
819 "zero deadline never completes"
820 );
821 }
822
823 /// STATEMENT: `Sleep` and `Deadline` wake only the most recently registered task
824 /// when they elapse, and a superseded waiter still observes completion.
825 ///
826 /// HOW:
827 /// - Poll each long timer with two distinct counted wakers, then `elapse` it.
828 /// - Check only the second waker was woken once and re-polling with the first
829 /// is ready.
830 #[ntex::test]
831 async fn single_waiter_wakes_latest_task_only() {
832 use crate::task::hooks::counted_waker;
833
834 let poll_pair = |poll: &dyn Fn(&mut task::Context<'_>) -> Poll<()>, elapse: &dyn Fn()| {
835 let (first, first_waker) = counted_waker();
836 let (second, second_waker) = counted_waker();
837 let mut first_cx = task::Context::from_waker(&first_waker);
838 let mut second_cx = task::Context::from_waker(&second_waker);
839
840 assert_eq!(poll(&mut first_cx), Poll::Pending);
841 assert_eq!(poll(&mut second_cx), Poll::Pending);
842 elapse();
843 assert_eq!((first.get(), second.get()), (0, 1));
844 assert_eq!(poll(&mut first_cx), Poll::Ready(()));
845 };
846
847 let slp = Sleep::new(Millis(10_000));
848 poll_pair(&|cx| slp.poll_elapsed(cx), &|| slp.elapse());
849
850 let dl = Deadline::new(Millis(10_000));
851 let hnd = dl.hnd.as_ref().unwrap();
852 poll_pair(&|cx| dl.poll_elapsed(cx), &|| hnd.elapse());
853 }
854
855 /// STATEMENT: Timers with different deadlines progress alongside a recurring interval.
856 ///
857 /// HOW:
858 /// - Spawn an interval task and await shorter and longer sleeps followed by another short sleep.
859 /// - On non-macOS targets, verify each elapsed duration stays within its configured bounds.
860 #[ntex::test]
861 #[allow(unused_variables, clippy::used_underscore_binding)]
862 async fn test_timer() {
863 crate::spawn(async {
864 let s = interval(Millis(25));
865 loop {
866 s.tick().await;
867 }
868 });
869 let time = Instant::now();
870 let fut1 = sleep(Millis(1000));
871 let fut2 = sleep(Millis(200));
872
873 fut2.await;
874 #[cfg(not(target_os = "macos"))]
875 {
876 let _elapsed = time.elapsed();
877 assert!(
878 _elapsed > time::Duration::from_millis(200)
879 && _elapsed < time::Duration::from_millis(300),
880 "elapsed: {_elapsed:?}"
881 );
882 }
883
884 fut1.await;
885
886 #[cfg(not(target_os = "macos"))]
887 {
888 let _elapsed = time.elapsed();
889 assert!(
890 _elapsed > time::Duration::from_secs(1)
891 && _elapsed < time::Duration::from_millis(1200), // osx
892 "elapsed: {_elapsed:?}",
893 );
894 }
895
896 let time = Instant::now();
897 sleep(Millis(25)).await;
898 #[cfg(not(target_os = "macos"))]
899 {
900 let _elapsed = time.elapsed();
901 assert!(
902 _elapsed > time::Duration::from_millis(20)
903 && _elapsed < time::Duration::from_millis(50),
904 "elapsed: {_elapsed:?}",
905 );
906 }
907 }
908
909 /// STATEMENT: The timer futures and `CallbackTimer` hold a thread-local timer
910 /// handle, so they are not `Send`.
911 ///
912 /// HOW:
913 /// - Define a trait with a blanket impl for all types and a second impl for
914 /// `Send` types.
915 /// - Resolve the trait item with an inferred parameter for `Sleep`, `Deadline`,
916 /// `Interval`, and `CallbackTimer`; it compiles only if exactly one impl
917 /// applies, i.e. the type is not `Send`.
918 #[test]
919 fn timer_futures_are_thread_local() {
920 trait NotSend<A> {
921 fn check() {}
922 }
923 impl<T: ?Sized> NotSend<()> for T {}
924 impl<T: ?Sized + Send> NotSend<u8> for T {}
925
926 <Sleep as NotSend<_>>::check();
927 <Deadline as NotSend<_>>::check();
928 <Interval as NotSend<_>>::check();
929 <CallbackTimer as NotSend<_>>::check();
930 }
931}