Coverage Report

Created: 2026-07-25 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.53.1/src/time/sleep.rs
Line
Count
Source
1
use crate::runtime::{scheduler, Timer};
2
use crate::time::{error::Error, Duration, Instant};
3
use crate::util::trace;
4
5
use pin_project_lite::pin_project;
6
use std::future::Future;
7
use std::panic::Location;
8
use std::pin::Pin;
9
use 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]
62
0
pub fn sleep_until(deadline: Instant) -> Sleep {
63
0
    Sleep::new_timeout(deadline, trace::caller_location())
64
0
}
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]
123
0
pub fn sleep(duration: Duration) -> Sleep {
124
0
    let location = trace::caller_location();
125
126
0
    match Instant::now().checked_add(duration) {
127
0
        Some(deadline) => Sleep::new_timeout(deadline, location),
128
0
        None => Sleep::new_timeout(Instant::far_future(), location),
129
    }
130
0
}
131
132
pin_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
234
cfg_trace! {
235
    #[derive(Debug)]
236
    struct Inner {
237
        ctx: trace::AsyncOpTracingCtx,
238
    }
239
}
240
241
cfg_not_trace! {
242
    #[derive(Debug)]
243
    struct Inner {
244
    }
245
}
246
247
impl Sleep {
248
    #[cfg_attr(not(all(tokio_unstable, feature = "tracing")), allow(unused_variables))]
249
    #[track_caller]
250
0
    pub(crate) fn new_timeout(
251
0
        deadline: Instant,
252
0
        location: Option<&'static Location<'static>>,
253
0
    ) -> Sleep {
254
0
        let handle = scheduler::Handle::current();
255
        // Panic if the time driver is not enabled (backwards compat)
256
0
        _ = 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
0
        let inner = Inner {};
290
291
0
        Sleep {
292
0
            deadline,
293
0
            driver: handle,
294
0
            inner,
295
0
            timer: None,
296
0
        }
297
0
    }
298
299
0
    pub(crate) fn far_future(location: Option<&'static Location<'static>>) -> Sleep {
300
0
        Self::new_timeout(Instant::far_future(), location)
301
0
    }
302
303
    /// Returns the instant at which the future will complete.
304
0
    pub fn deadline(&self) -> Instant {
305
0
        self.deadline
306
0
    }
307
308
    /// Returns `true` if `Sleep` has elapsed.
309
    ///
310
    /// A `Sleep` instance is elapsed when the requested duration has elapsed.
311
0
    pub fn is_elapsed(&self) -> bool {
312
0
        self.timer.as_ref().is_some_and(Timer::is_elapsed)
313
0
    }
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
0
    pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
345
0
        let mut this = self.project();
346
0
        *this.deadline = deadline;
347
348
0
        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
0
        match this.timer.as_mut().as_pin_mut() {
373
0
            Some(timer) => timer.reset(handle.clone(), deadline),
374
0
            None => {
375
0
                let timer = Timer::new(handle.clone(), deadline);
376
0
                this.timer.set(Some(timer));
377
0
                this.timer.as_pin_mut().unwrap().init(deadline);
378
0
            }
379
        }
380
0
    }
381
382
    /// Resets the `Sleep` instance to a new deadline.
383
    ///
384
    /// Unlike [`reset`][Self::reset], this __removes__ the internal timer.
385
0
    pub(super) fn reset_without_timer(self: Pin<&mut Self>, deadline: Instant) {
386
0
        let mut this = self.project();
387
0
        *this.deadline = deadline;
388
0
        this.timer.set(None);
389
0
    }
390
391
0
    fn poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> {
392
0
        ready!(crate::trace::trace_leaf());
393
0
        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
0
        let coop = ready!(crate::task::coop::poll_proceed(cx));
411
412
0
        let timer = match this.timer.as_mut().as_pin_mut() {
413
0
            Some(timer) => timer,
414
            None => {
415
0
                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
0
                let timer = Timer::new(handle.clone(), *this.deadline);
432
0
                this.timer.set(Some(timer));
433
0
                let mut timer = this.timer.as_pin_mut().unwrap();
434
0
                timer.as_mut().init(*this.deadline);
435
0
                timer
436
            }
437
        };
438
439
0
        let result = timer.poll_elapsed(cx).map(move |r| {
440
0
            coop.made_progress();
441
0
            r
442
0
        });
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
0
        return result;
449
0
    }
450
}
451
452
impl 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
0
    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
465
0
        match ready!(self.poll_elapsed(cx)) {
466
0
            Ok(()) => Poll::Ready(()),
467
0
            Err(e) => panic!("timer error: {e}"),
468
        }
469
0
    }
470
}