tokio/time/sleep.rs
1use crate::runtime::{scheduler, Timer};
2use crate::time::{error::Error, 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 location = trace::caller_location();
125
126 match Instant::now().checked_add(duration) {
127 Some(deadline) => Sleep::new_timeout(deadline, location),
128 None => Sleep::new_timeout(Instant::far_future(), location),
129 }
130}
131
132pin_project! {
133 /// Future returned by [`sleep`](sleep) and [`sleep_until`](sleep_until).
134 ///
135 /// This type does not implement the `Unpin` trait, which means that if you
136 /// use it with [`select!`] or by calling `poll`, you have to pin it first.
137 /// If you use it with `.await`, this does not apply.
138 ///
139 /// # Examples
140 ///
141 /// Wait 100ms and print "100 ms have elapsed".
142 ///
143 /// ```
144 /// use tokio::time::{sleep, Duration};
145 ///
146 /// # #[tokio::main(flavor = "current_thread")]
147 /// # async fn main() {
148 /// sleep(Duration::from_millis(100)).await;
149 /// println!("100 ms have elapsed");
150 /// # }
151 /// ```
152 ///
153 /// Use with [`select!`]. Pinning the `Sleep` with [`tokio::pin!`] is
154 /// necessary when the same `Sleep` is selected on multiple times.
155 /// ```no_run
156 /// use tokio::time::{self, Duration, Instant};
157 ///
158 /// # #[tokio::main(flavor = "current_thread")]
159 /// # async fn main() {
160 /// let sleep = time::sleep(Duration::from_millis(10));
161 /// tokio::pin!(sleep);
162 ///
163 /// loop {
164 /// tokio::select! {
165 /// () = &mut sleep => {
166 /// println!("timer elapsed");
167 /// sleep.as_mut().reset(Instant::now() + Duration::from_millis(50));
168 /// },
169 /// }
170 /// }
171 /// # }
172 /// ```
173 /// Use in a struct with boxing. By pinning the `Sleep` with a `Box`, the
174 /// `HasSleep` struct implements `Unpin`, even though `Sleep` does not.
175 /// ```
176 /// use std::future::Future;
177 /// use std::pin::Pin;
178 /// use std::task::{Context, Poll};
179 /// use tokio::time::Sleep;
180 ///
181 /// struct HasSleep {
182 /// sleep: Pin<Box<Sleep>>,
183 /// }
184 ///
185 /// impl Future for HasSleep {
186 /// type Output = ();
187 ///
188 /// fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
189 /// self.sleep.as_mut().poll(cx)
190 /// }
191 /// }
192 /// ```
193 /// Use in a struct with pin projection. This method avoids the `Box`, but
194 /// the `HasSleep` struct will not be `Unpin` as a consequence.
195 /// ```
196 /// use std::future::Future;
197 /// use std::pin::Pin;
198 /// use std::task::{Context, Poll};
199 /// use tokio::time::Sleep;
200 /// use pin_project_lite::pin_project;
201 ///
202 /// pin_project! {
203 /// struct HasSleep {
204 /// #[pin]
205 /// sleep: Sleep,
206 /// }
207 /// }
208 ///
209 /// impl Future for HasSleep {
210 /// type Output = ();
211 ///
212 /// fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
213 /// self.project().sleep.poll(cx)
214 /// }
215 /// }
216 /// ```
217 ///
218 /// [`select!`]: ../macro.select.html
219 /// [`tokio::pin!`]: ../macro.pin.html
220 #[project(!Unpin)]
221 // Alias for old name in 0.2
222 #[cfg_attr(docsrs, doc(alias = "Delay"))]
223 #[derive(Debug)]
224 #[must_use = "futures do nothing unless you `.await` or poll them"]
225 pub struct Sleep {
226 deadline: Instant,
227 driver: scheduler::Handle,
228 inner: Inner,
229 #[pin]
230 timer: Option<Timer>,
231 }
232}
233
234cfg_trace! {
235 #[derive(Debug)]
236 struct Inner {
237 ctx: trace::AsyncOpTracingCtx,
238 }
239}
240
241cfg_not_trace! {
242 #[derive(Debug)]
243 struct Inner {
244 }
245}
246
247impl Sleep {
248 #[cfg_attr(not(all(tokio_unstable, feature = "tracing")), allow(unused_variables))]
249 #[track_caller]
250 pub(crate) fn new_timeout(
251 deadline: Instant,
252 location: Option<&'static Location<'static>>,
253 ) -> Sleep {
254 let handle = scheduler::Handle::current();
255 // Panic if the time driver is not enabled (backwards compat)
256 _ = handle.driver().time();
257 #[cfg(all(tokio_unstable, feature = "tracing"))]
258 let inner = {
259 let location = location.expect("should have location if tracing");
260 let resource_span = tracing::trace_span!(
261 parent: None,
262 "runtime.resource",
263 concrete_type = "Sleep",
264 kind = "timer",
265 loc.file = location.file(),
266 loc.line = location.line(),
267 loc.col = location.column(),
268 );
269
270 let async_op_span = tracing::trace_span!(
271 parent: &resource_span,
272 "runtime.resource.async_op",
273 source = "Sleep::new_timeout",
274 );
275
276 let async_op_poll_span =
277 tracing::trace_span!(parent: &async_op_span, "runtime.resource.async_op.poll");
278
279 let ctx = trace::AsyncOpTracingCtx {
280 async_op_span,
281 async_op_poll_span,
282 resource_span,
283 };
284
285 Inner { ctx }
286 };
287
288 #[cfg(not(all(tokio_unstable, feature = "tracing")))]
289 let inner = Inner {};
290
291 Sleep {
292 deadline,
293 driver: handle,
294 inner,
295 timer: None,
296 }
297 }
298
299 pub(crate) fn far_future(location: Option<&'static Location<'static>>) -> Sleep {
300 Self::new_timeout(Instant::far_future(), location)
301 }
302
303 /// Returns the instant at which the future will complete.
304 pub fn deadline(&self) -> Instant {
305 self.deadline
306 }
307
308 /// Returns `true` if `Sleep` has elapsed.
309 ///
310 /// A `Sleep` instance is elapsed when the requested duration has elapsed.
311 pub fn is_elapsed(&self) -> bool {
312 self.timer.as_ref().is_some_and(Timer::is_elapsed)
313 }
314
315 /// Resets the `Sleep` instance to a new deadline.
316 ///
317 /// Calling this function allows changing the instant at which the `Sleep`
318 /// future completes without having to create new associated state.
319 ///
320 /// This function can be called both before and after the future has
321 /// completed.
322 ///
323 /// To call this method, you will usually combine the call with
324 /// [`Pin::as_mut`], which lets you call the method without consuming the
325 /// `Sleep` itself.
326 ///
327 /// # Example
328 ///
329 /// ```
330 /// use tokio::time::{Duration, Instant};
331 ///
332 /// # #[tokio::main(flavor = "current_thread")]
333 /// # async fn main() {
334 /// let sleep = tokio::time::sleep(Duration::from_millis(10));
335 /// tokio::pin!(sleep);
336 ///
337 /// sleep.as_mut().reset(Instant::now() + Duration::from_millis(20));
338 /// # }
339 /// ```
340 ///
341 /// See also the top-level examples.
342 ///
343 /// [`Pin::as_mut`]: fn@std::pin::Pin::as_mut
344 pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
345 let mut this = self.project();
346 *this.deadline = deadline;
347
348 let handle = this.driver;
349
350 #[cfg(all(tokio_unstable, feature = "tracing"))]
351 {
352 let _resource_enter = this.inner.ctx.resource_span.enter();
353 this.inner.ctx.async_op_span =
354 tracing::trace_span!("runtime.resource.async_op", source = "Sleep::reset");
355 let _async_op_enter = this.inner.ctx.async_op_span.enter();
356
357 this.inner.ctx.async_op_poll_span =
358 tracing::trace_span!("runtime.resource.async_op.poll");
359
360 let clock = handle.driver().clock();
361 let time_source = handle.driver().time().time_source();
362 let now = time_source.now(clock);
363 let tick = time_source.deadline_to_tick(deadline);
364 tracing::trace!(
365 target: "runtime::resource::state_update",
366 duration = tick.saturating_sub(now),
367 duration.unit = "ms",
368 duration.op = "override",
369 );
370 }
371
372 match this.timer.as_mut().as_pin_mut() {
373 Some(timer) => timer.reset(handle.clone(), deadline),
374 None => {
375 let timer = Timer::new(handle.clone(), deadline);
376 this.timer.set(Some(timer));
377 this.timer.as_pin_mut().unwrap().init(deadline);
378 }
379 }
380 }
381
382 /// Resets the `Sleep` instance to a new deadline.
383 ///
384 /// Unlike [`reset`][Self::reset], this __removes__ the internal timer.
385 pub(super) fn reset_without_timer(self: Pin<&mut Self>, deadline: Instant) {
386 let mut this = self.project();
387 *this.deadline = deadline;
388 this.timer.set(None);
389 }
390
391 fn poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> {
392 ready!(crate::trace::trace_leaf());
393 let mut this = self.project();
394
395 #[cfg(all(tokio_unstable, feature = "tracing"))]
396 let _res_span = this.inner.ctx.resource_span.enter();
397 #[cfg(all(tokio_unstable, feature = "tracing"))]
398 let _ao_span = this.inner.ctx.async_op_span.enter();
399 #[cfg(all(tokio_unstable, feature = "tracing"))]
400 let _ao_poll_span = this.inner.ctx.async_op_poll_span.enter();
401
402 // Keep track of task budget
403 #[cfg(all(tokio_unstable, feature = "tracing"))]
404 let coop = ready!(trace_poll_op!(
405 "poll_elapsed",
406 crate::task::coop::poll_proceed(cx),
407 ));
408
409 #[cfg(any(not(tokio_unstable), not(feature = "tracing")))]
410 let coop = ready!(crate::task::coop::poll_proceed(cx));
411
412 let timer = match this.timer.as_mut().as_pin_mut() {
413 Some(timer) => timer,
414 None => {
415 let handle = this.driver;
416
417 #[cfg(all(tokio_unstable, feature = "tracing"))]
418 {
419 let clock = handle.driver().clock();
420 let time_source = handle.driver().time().time_source();
421 let now = time_source.now(clock);
422 let tick = time_source.deadline_to_tick(*this.deadline);
423 tracing::trace!(
424 target: "runtime::resource::state_update",
425 duration = tick.saturating_sub(now),
426 duration.unit = "ms",
427 duration.op = "override",
428 );
429 }
430
431 let timer = Timer::new(handle.clone(), *this.deadline);
432 this.timer.set(Some(timer));
433 let mut timer = this.timer.as_pin_mut().unwrap();
434 timer.as_mut().init(*this.deadline);
435 timer
436 }
437 };
438
439 let result = timer.poll_elapsed(cx).map(move |r| {
440 coop.made_progress();
441 r
442 });
443
444 #[cfg(all(tokio_unstable, feature = "tracing"))]
445 return trace_poll_op!("poll_elapsed", result);
446
447 #[cfg(any(not(tokio_unstable), not(feature = "tracing")))]
448 return result;
449 }
450}
451
452impl Future for Sleep {
453 type Output = ();
454
455 // `poll_elapsed` can return an error in two cases:
456 //
457 // - AtCapacity: this is a pathological case where far too many
458 // sleep instances have been scheduled.
459 // - Shutdown: No timer has been setup, which is a misuse error.
460 //
461 // Both cases are extremely rare, and pretty accurately fit into
462 // "logic errors", so we just panic in this case. A user couldn't
463 // really do much better if we passed the error onwards.
464 fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
465 match ready!(self.poll_elapsed(cx)) {
466 Ok(()) => Poll::Ready(()),
467 Err(e) => panic!("timer error: {e}"),
468 }
469 }
470}