Skip to main content

tokio/time/
sleep.rs

1use crate::runtime::{scheduler, Timer};
2use crate::time::{error::Error, safe_delay, Duration, Instant};
3use crate::util::trace;
4
5use pin_project_lite::pin_project;
6use std::future::Future;
7use std::panic::Location;
8use std::pin::Pin;
9use std::task::{self, ready, Poll};
10
11/// Waits until `deadline` is reached.
12///
13/// No work is performed while awaiting on the sleep future to complete. `Sleep`
14/// operates at millisecond granularity and should not be used for tasks that
15/// require high-resolution timers.
16///
17/// To run something regularly on a schedule, see [`interval`].
18///
19/// # Cancellation
20///
21/// Canceling a sleep instance is done by dropping the returned future. No additional
22/// cleanup work is required.
23///
24/// # Examples
25///
26/// Wait 100ms and print "100 ms have elapsed".
27///
28/// ```
29/// use tokio::time::{sleep_until, Instant, Duration};
30///
31/// # #[tokio::main(flavor = "current_thread")]
32/// # async fn main() {
33/// sleep_until(Instant::now() + Duration::from_millis(100)).await;
34/// println!("100 ms have elapsed");
35/// # }
36/// ```
37///
38/// See the documentation for the [`Sleep`] type for more examples.
39///
40/// # Panics
41///
42/// This function panics if there is no current timer set.
43///
44/// It can be triggered when [`Builder::enable_time`] or
45/// [`Builder::enable_all`] are not included in the builder.
46///
47/// It can also panic whenever a timer is created outside of a
48/// Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
49/// since the function is executed outside of the runtime.
50/// Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
51/// And this is because wrapping the function on an async makes it lazy,
52/// and so gets executed inside the runtime successfully without
53/// panicking.
54///
55/// [`Sleep`]: struct@crate::time::Sleep
56/// [`interval`]: crate::time::interval()
57/// [`Builder::enable_time`]: crate::runtime::Builder::enable_time
58/// [`Builder::enable_all`]: crate::runtime::Builder::enable_all
59// Alias for old name in 0.x
60#[cfg_attr(docsrs, doc(alias = "delay_until"))]
61#[track_caller]
62pub fn sleep_until(deadline: Instant) -> Sleep {
63    Sleep::new_timeout(deadline, trace::caller_location())
64}
65
66/// Waits until `duration` has elapsed.
67///
68/// Equivalent to `sleep_until(Instant::now() + duration)`. An asynchronous
69/// analog to `std::thread::sleep`.
70///
71/// No work is performed while awaiting on the sleep future to complete. `Sleep`
72/// operates at millisecond granularity and should not be used for tasks that
73/// require high-resolution timers. The implementation is platform specific,
74/// and some platforms (specifically Windows) will provide timers with a
75/// larger resolution than 1 ms.
76///
77/// To run something regularly on a schedule, see [`interval`].
78///
79/// # Cancellation
80///
81/// Canceling a sleep instance is done by dropping the returned future. No additional
82/// cleanup work is required.
83///
84/// # Examples
85///
86/// Wait 100ms and print "100 ms have elapsed".
87///
88/// ```
89/// use tokio::time::{sleep, Duration};
90///
91/// # #[tokio::main(flavor = "current_thread")]
92/// # async fn main() {
93/// sleep(Duration::from_millis(100)).await;
94/// println!("100 ms have elapsed");
95/// # }
96/// ```
97///
98/// See the documentation for the [`Sleep`] type for more examples.
99///
100/// # Panics
101///
102/// This function panics if there is no current timer set.
103///
104/// It can be triggered when [`Builder::enable_time`] or
105/// [`Builder::enable_all`] are not included in the builder.
106///
107/// It can also panic whenever a timer is created outside of a
108/// Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
109/// since the function is executed outside of the runtime.
110/// Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
111/// And this is because wrapping the function on an async makes it lazy,
112/// and so gets executed inside the runtime successfully without
113/// panicking.
114///
115/// [`Sleep`]: struct@crate::time::Sleep
116/// [`interval`]: crate::time::interval()
117/// [`Builder::enable_time`]: crate::runtime::Builder::enable_time
118/// [`Builder::enable_all`]: crate::runtime::Builder::enable_all
119// Alias for old name in 0.x
120#[cfg_attr(docsrs, doc(alias = "delay_for"))]
121#[cfg_attr(docsrs, doc(alias = "wait"))]
122#[track_caller]
123pub fn sleep(duration: Duration) -> Sleep {
124    let deadline = Instant::now() + safe_delay(duration);
125    Sleep::new_timeout(deadline, trace::caller_location())
126}
127
128pin_project! {
129    /// Future returned by [`sleep`](sleep) and [`sleep_until`](sleep_until).
130    ///
131    /// This type does not implement the `Unpin` trait, which means that if you
132    /// use it with [`select!`] or by calling `poll`, you have to pin it first.
133    /// If you use it with `.await`, this does not apply.
134    ///
135    /// # Examples
136    ///
137    /// Wait 100ms and print "100 ms have elapsed".
138    ///
139    /// ```
140    /// use tokio::time::{sleep, Duration};
141    ///
142    /// # #[tokio::main(flavor = "current_thread")]
143    /// # async fn main() {
144    /// sleep(Duration::from_millis(100)).await;
145    /// println!("100 ms have elapsed");
146    /// # }
147    /// ```
148    ///
149    /// Use with [`select!`]. Pinning the `Sleep` with [`tokio::pin!`] is
150    /// necessary when the same `Sleep` is selected on multiple times.
151    /// ```no_run
152    /// use tokio::time::{self, Duration, Instant};
153    ///
154    /// # #[tokio::main(flavor = "current_thread")]
155    /// # async fn main() {
156    /// let sleep = time::sleep(Duration::from_millis(10));
157    /// tokio::pin!(sleep);
158    ///
159    /// loop {
160    ///     tokio::select! {
161    ///         () = &mut sleep => {
162    ///             println!("timer elapsed");
163    ///             sleep.as_mut().reset(Instant::now() + Duration::from_millis(50));
164    ///         },
165    ///     }
166    /// }
167    /// # }
168    /// ```
169    /// Use in a struct with boxing. By pinning the `Sleep` with a `Box`, the
170    /// `HasSleep` struct implements `Unpin`, even though `Sleep` does not.
171    /// ```
172    /// use std::future::Future;
173    /// use std::pin::Pin;
174    /// use std::task::{Context, Poll};
175    /// use tokio::time::Sleep;
176    ///
177    /// struct HasSleep {
178    ///     sleep: Pin<Box<Sleep>>,
179    /// }
180    ///
181    /// impl Future for HasSleep {
182    ///     type Output = ();
183    ///
184    ///     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
185    ///         self.sleep.as_mut().poll(cx)
186    ///     }
187    /// }
188    /// ```
189    /// Use in a struct with pin projection. This method avoids the `Box`, but
190    /// the `HasSleep` struct will not be `Unpin` as a consequence.
191    /// ```
192    /// use std::future::Future;
193    /// use std::pin::Pin;
194    /// use std::task::{Context, Poll};
195    /// use tokio::time::Sleep;
196    /// use pin_project_lite::pin_project;
197    ///
198    /// pin_project! {
199    ///     struct HasSleep {
200    ///         #[pin]
201    ///         sleep: Sleep,
202    ///     }
203    /// }
204    ///
205    /// impl Future for HasSleep {
206    ///     type Output = ();
207    ///
208    ///     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
209    ///         self.project().sleep.poll(cx)
210    ///     }
211    /// }
212    /// ```
213    ///
214    /// [`select!`]: ../macro.select.html
215    /// [`tokio::pin!`]: ../macro.pin.html
216    #[project(!Unpin)]
217    // Alias for old name in 0.2
218    #[cfg_attr(docsrs, doc(alias = "Delay"))]
219    #[derive(Debug)]
220    #[must_use = "futures do nothing unless you `.await` or poll them"]
221    pub struct Sleep {
222        deadline: Instant,
223        driver: scheduler::Handle,
224        inner: Inner,
225        #[pin]
226        timer: Option<Timer>,
227    }
228
229    impl PinnedDrop for Sleep {
230        fn drop(this: Pin<&mut Self>) {
231            let this = this.project();
232            if let Some(timer) = this.timer.as_pin_mut() {
233                timer.cancel(this.driver);
234            }
235        }
236    }
237}
238
239cfg_trace! {
240    #[derive(Debug)]
241    struct Inner {
242        ctx: trace::AsyncOpTracingCtx,
243    }
244}
245
246cfg_not_trace! {
247    #[derive(Debug)]
248    struct Inner {
249    }
250}
251
252impl Sleep {
253    #[cfg_attr(not(all(tokio_unstable, feature = "tracing")), allow(unused_variables))]
254    #[track_caller]
255    pub(crate) fn new_timeout(
256        deadline: Instant,
257        location: Option<&'static Location<'static>>,
258    ) -> Sleep {
259        let handle = scheduler::Handle::current();
260        // Panic if the time driver is not enabled (backwards compat)
261        _ = handle.driver().time();
262        #[cfg(all(tokio_unstable, feature = "tracing"))]
263        let inner = {
264            let location = location.expect("should have location if tracing");
265            let resource_span = tracing::trace_span!(
266                parent: None,
267                "runtime.resource",
268                concrete_type = "Sleep",
269                kind = "timer",
270                loc.file = location.file(),
271                loc.line = location.line(),
272                loc.col = location.column(),
273            );
274
275            let async_op_span = tracing::trace_span!(
276                parent: &resource_span,
277                "runtime.resource.async_op",
278                source = "Sleep::new_timeout",
279            );
280
281            let async_op_poll_span =
282                tracing::trace_span!(parent: &async_op_span, "runtime.resource.async_op.poll");
283
284            let ctx = trace::AsyncOpTracingCtx {
285                async_op_span,
286                async_op_poll_span,
287                resource_span,
288            };
289
290            Inner { ctx }
291        };
292
293        #[cfg(not(all(tokio_unstable, feature = "tracing")))]
294        let inner = Inner {};
295
296        Sleep {
297            deadline,
298            driver: handle,
299            inner,
300            timer: None,
301        }
302    }
303
304    /// Returns the instant at which the future will complete.
305    pub fn deadline(&self) -> Instant {
306        self.deadline
307    }
308
309    /// Returns `true` if `Sleep` has elapsed.
310    ///
311    /// A `Sleep` instance is elapsed when the requested duration has elapsed.
312    pub fn is_elapsed(&self) -> bool {
313        self.timer.as_ref().is_some_and(Timer::is_elapsed)
314    }
315
316    /// Resets the `Sleep` instance to a new deadline.
317    ///
318    /// Calling this function allows changing the instant at which the `Sleep`
319    /// future completes without having to create new associated state.
320    ///
321    /// This function can be called both before and after the future has
322    /// completed.
323    ///
324    /// To call this method, you will usually combine the call with
325    /// [`Pin::as_mut`], which lets you call the method without consuming the
326    /// `Sleep` itself.
327    ///
328    /// # Example
329    ///
330    /// ```
331    /// use tokio::time::{Duration, Instant};
332    ///
333    /// # #[tokio::main(flavor = "current_thread")]
334    /// # async fn main() {
335    /// let sleep = tokio::time::sleep(Duration::from_millis(10));
336    /// tokio::pin!(sleep);
337    ///
338    /// sleep.as_mut().reset(Instant::now() + Duration::from_millis(20));
339    /// # }
340    /// ```
341    ///
342    /// See also the top-level examples.
343    ///
344    /// [`Pin::as_mut`]: fn@std::pin::Pin::as_mut
345    pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
346        let mut this = self.project();
347        *this.deadline = deadline;
348
349        let handle = this.driver;
350        let time_source = handle.driver().time().time_source();
351        let deadline = time_source.deadline_to_tick(deadline);
352
353        #[cfg(all(tokio_unstable, feature = "tracing"))]
354        {
355            let _resource_enter = this.inner.ctx.resource_span.enter();
356            this.inner.ctx.async_op_span =
357                tracing::trace_span!("runtime.resource.async_op", source = "Sleep::reset");
358            let _async_op_enter = this.inner.ctx.async_op_span.enter();
359
360            this.inner.ctx.async_op_poll_span =
361                tracing::trace_span!("runtime.resource.async_op.poll");
362
363            let clock = handle.driver().clock();
364            let now = time_source.now(clock);
365            tracing::trace!(
366                target: "runtime::resource::state_update",
367                duration = deadline.saturating_sub(now),
368                duration.unit = "ms",
369                duration.op = "override",
370            );
371        }
372
373        match this.timer.as_mut().as_pin_mut() {
374            Some(timer) => timer.reset(handle, deadline),
375            None => {
376                let timer = Timer::new(handle, deadline);
377                this.timer.set(Some(timer));
378                this.timer.as_pin_mut().unwrap().init(handle, deadline);
379            }
380        }
381    }
382
383    /// Resets the `Sleep` instance to a new deadline.
384    ///
385    /// Unlike [`reset`][Self::reset], this __removes__ the internal timer.
386    ///
387    /// # Safety
388    ///
389    /// The internal timer must be elapsed.
390    pub(super) unsafe fn reset_without_timer(self: Pin<&mut Self>, deadline: Instant) {
391        let mut this = self.project();
392        *this.deadline = deadline;
393        this.timer.set(None);
394    }
395
396    fn poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> {
397        ready!(crate::trace::trace_leaf(cx));
398        let mut this = self.project();
399
400        #[cfg(all(tokio_unstable, feature = "tracing"))]
401        let _res_span = this.inner.ctx.resource_span.enter();
402        #[cfg(all(tokio_unstable, feature = "tracing"))]
403        let _ao_span = this.inner.ctx.async_op_span.enter();
404        #[cfg(all(tokio_unstable, feature = "tracing"))]
405        let _ao_poll_span = this.inner.ctx.async_op_poll_span.enter();
406
407        // Keep track of task budget
408        #[cfg(all(tokio_unstable, feature = "tracing"))]
409        let coop = ready!(trace_poll_op!(
410            "poll_elapsed",
411            crate::task::coop::poll_proceed(cx),
412        ));
413
414        #[cfg(any(not(tokio_unstable), not(feature = "tracing")))]
415        let coop = ready!(crate::task::coop::poll_proceed(cx));
416
417        let handle = this.driver;
418        let timer = match this.timer.as_mut().as_pin_mut() {
419            Some(timer) => timer,
420            None => {
421                let time_source = handle.driver().time().time_source();
422                let deadline = time_source.deadline_to_tick(*this.deadline);
423
424                #[cfg(all(tokio_unstable, feature = "tracing"))]
425                {
426                    let clock = handle.driver().clock();
427                    let now = time_source.now(clock);
428                    tracing::trace!(
429                        target: "runtime::resource::state_update",
430                        duration = deadline.saturating_sub(now),
431                        duration.unit = "ms",
432                        duration.op = "override",
433                    );
434                }
435
436                let timer = Timer::new(handle, deadline);
437                this.timer.set(Some(timer));
438                let mut timer = this.timer.as_pin_mut().unwrap();
439                timer.as_mut().init(handle, deadline);
440                timer
441            }
442        };
443
444        let result = timer.poll_elapsed(cx, handle).map(move |r| {
445            coop.made_progress();
446            r
447        });
448
449        #[cfg(all(tokio_unstable, feature = "tracing"))]
450        return trace_poll_op!("poll_elapsed", result);
451
452        #[cfg(any(not(tokio_unstable), not(feature = "tracing")))]
453        return result;
454    }
455}
456
457impl Future for Sleep {
458    type Output = ();
459
460    // `poll_elapsed` can return an error in two cases:
461    //
462    // - AtCapacity: this is a pathological case where far too many
463    //   sleep instances have been scheduled.
464    // - Shutdown: No timer has been setup, which is a misuse error.
465    //
466    // Both cases are extremely rare, and pretty accurately fit into
467    // "logic errors", so we just panic in this case. A user couldn't
468    // really do much better if we passed the error onwards.
469    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
470        match ready!(self.poll_elapsed(cx)) {
471            Ok(()) => Poll::Ready(()),
472            Err(e) => panic!("timer error: {e}"),
473        }
474    }
475}