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