1 use crate::time::driver::{Handle, TimerEntry};
2 use crate::time::{error::Error, Duration, Instant};
3 
4 use pin_project_lite::pin_project;
5 use std::future::Future;
6 use std::pin::Pin;
7 use std::task::{self, Poll};
8 
9 /// Waits until `deadline` is reached.
10 ///
11 /// No work is performed while awaiting on the sleep future to complete. `Sleep`
12 /// operates at millisecond granularity and should not be used for tasks that
13 /// require high-resolution timers.
14 ///
15 /// # Cancellation
16 ///
17 /// Canceling a sleep instance is done by dropping the returned future. No additional
18 /// cleanup work is required.
19 // Alias for old name in 0.x
20 #[cfg_attr(docsrs, doc(alias = "delay_until"))]
sleep_until(deadline: Instant) -> Sleep21 pub fn sleep_until(deadline: Instant) -> Sleep {
22     Sleep::new_timeout(deadline)
23 }
24 
25 /// Waits until `duration` has elapsed.
26 ///
27 /// Equivalent to `sleep_until(Instant::now() + duration)`. An asynchronous
28 /// analog to `std::thread::sleep`.
29 ///
30 /// No work is performed while awaiting on the sleep future to complete. `Sleep`
31 /// operates at millisecond granularity and should not be used for tasks that
32 /// require high-resolution timers.
33 ///
34 /// To run something regularly on a schedule, see [`interval`].
35 ///
36 /// The maximum duration for a sleep is 68719476734 milliseconds (approximately 2.2 years).
37 ///
38 /// # Cancellation
39 ///
40 /// Canceling a sleep instance is done by dropping the returned future. No additional
41 /// cleanup work is required.
42 ///
43 /// # Examples
44 ///
45 /// Wait 100ms and print "100 ms have elapsed".
46 ///
47 /// ```
48 /// use tokio::time::{sleep, Duration};
49 ///
50 /// #[tokio::main]
51 /// async fn main() {
52 ///     sleep(Duration::from_millis(100)).await;
53 ///     println!("100 ms have elapsed");
54 /// }
55 /// ```
56 ///
57 /// [`interval`]: crate::time::interval()
58 // Alias for old name in 0.x
59 #[cfg_attr(docsrs, doc(alias = "delay_for"))]
60 #[cfg_attr(docsrs, doc(alias = "wait"))]
sleep(duration: Duration) -> Sleep61 pub fn sleep(duration: Duration) -> Sleep {
62     match Instant::now().checked_add(duration) {
63         Some(deadline) => sleep_until(deadline),
64         None => sleep_until(Instant::far_future()),
65     }
66 }
67 
68 pin_project! {
69     /// Future returned by [`sleep`](sleep) and [`sleep_until`](sleep_until).
70     ///
71     /// This type does not implement the `Unpin` trait, which means that if you
72     /// use it with [`select!`] or by calling `poll`, you have to pin it first.
73     /// If you use it with `.await`, this does not apply.
74     ///
75     /// # Examples
76     ///
77     /// Wait 100ms and print "100 ms have elapsed".
78     ///
79     /// ```
80     /// use tokio::time::{sleep, Duration};
81     ///
82     /// #[tokio::main]
83     /// async fn main() {
84     ///     sleep(Duration::from_millis(100)).await;
85     ///     println!("100 ms have elapsed");
86     /// }
87     /// ```
88     ///
89     /// Use with [`select!`]. Pinning the `Sleep` with [`tokio::pin!`] is
90     /// necessary when the same `Sleep` is selected on multiple times.
91     /// ```no_run
92     /// use tokio::time::{self, Duration, Instant};
93     ///
94     /// #[tokio::main]
95     /// async fn main() {
96     ///     let sleep = time::sleep(Duration::from_millis(10));
97     ///     tokio::pin!(sleep);
98     ///
99     ///     loop {
100     ///         tokio::select! {
101     ///             () = &mut sleep => {
102     ///                 println!("timer elapsed");
103     ///                 sleep.as_mut().reset(Instant::now() + Duration::from_millis(50));
104     ///             },
105     ///         }
106     ///     }
107     /// }
108     /// ```
109     /// Use in a struct with boxing. By pinning the `Sleep` with a `Box`, the
110     /// `HasSleep` struct implements `Unpin`, even though `Sleep` does not.
111     /// ```
112     /// use std::future::Future;
113     /// use std::pin::Pin;
114     /// use std::task::{Context, Poll};
115     /// use tokio::time::Sleep;
116     ///
117     /// struct HasSleep {
118     ///     sleep: Pin<Box<Sleep>>,
119     /// }
120     ///
121     /// impl Future for HasSleep {
122     ///     type Output = ();
123     ///
124     ///     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
125     ///         self.sleep.as_mut().poll(cx)
126     ///     }
127     /// }
128     /// ```
129     /// Use in a struct with pin projection. This method avoids the `Box`, but
130     /// the `HasSleep` struct will not be `Unpin` as a consequence.
131     /// ```
132     /// use std::future::Future;
133     /// use std::pin::Pin;
134     /// use std::task::{Context, Poll};
135     /// use tokio::time::Sleep;
136     /// use pin_project_lite::pin_project;
137     ///
138     /// pin_project! {
139     ///     struct HasSleep {
140     ///         #[pin]
141     ///         sleep: Sleep,
142     ///     }
143     /// }
144     ///
145     /// impl Future for HasSleep {
146     ///     type Output = ();
147     ///
148     ///     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
149     ///         self.project().sleep.poll(cx)
150     ///     }
151     /// }
152     /// ```
153     ///
154     /// [`select!`]: ../macro.select.html
155     /// [`tokio::pin!`]: ../macro.pin.html
156     // Alias for old name in 0.2
157     #[cfg_attr(docsrs, doc(alias = "Delay"))]
158     #[derive(Debug)]
159     #[must_use = "futures do nothing unless you `.await` or poll them"]
160     pub struct Sleep {
161         deadline: Instant,
162 
163         // The link between the `Sleep` instance and the timer that drives it.
164         #[pin]
165         entry: TimerEntry,
166     }
167 }
168 
169 impl Sleep {
new_timeout(deadline: Instant) -> Sleep170     pub(crate) fn new_timeout(deadline: Instant) -> Sleep {
171         let handle = Handle::current();
172         let entry = TimerEntry::new(&handle, deadline);
173 
174         Sleep { deadline, entry }
175     }
176 
far_future() -> Sleep177     pub(crate) fn far_future() -> Sleep {
178         Self::new_timeout(Instant::far_future())
179     }
180 
181     /// Returns the instant at which the future will complete.
deadline(&self) -> Instant182     pub fn deadline(&self) -> Instant {
183         self.deadline
184     }
185 
186     /// Returns `true` if `Sleep` has elapsed.
187     ///
188     /// A `Sleep` instance is elapsed when the requested duration has elapsed.
is_elapsed(&self) -> bool189     pub fn is_elapsed(&self) -> bool {
190         self.entry.is_elapsed()
191     }
192 
193     /// Resets the `Sleep` instance to a new deadline.
194     ///
195     /// Calling this function allows changing the instant at which the `Sleep`
196     /// future completes without having to create new associated state.
197     ///
198     /// This function can be called both before and after the future has
199     /// completed.
200     ///
201     /// To call this method, you will usually combine the call with
202     /// [`Pin::as_mut`], which lets you call the method without consuming the
203     /// `Sleep` itself.
204     ///
205     /// # Example
206     ///
207     /// ```
208     /// use tokio::time::{Duration, Instant};
209     ///
210     /// # #[tokio::main(flavor = "current_thread")]
211     /// # async fn main() {
212     /// let sleep = tokio::time::sleep(Duration::from_millis(10));
213     /// tokio::pin!(sleep);
214     ///
215     /// sleep.as_mut().reset(Instant::now() + Duration::from_millis(20));
216     /// # }
217     /// ```
218     ///
219     /// [`Pin::as_mut`]: fn@std::pin::Pin::as_mut
reset(self: Pin<&mut Self>, deadline: Instant)220     pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
221         let me = self.project();
222         me.entry.reset(deadline);
223         *me.deadline = deadline;
224     }
225 
poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>>226     fn poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> {
227         let me = self.project();
228 
229         // Keep track of task budget
230         let coop = ready!(crate::coop::poll_proceed(cx));
231 
232         me.entry.poll_elapsed(cx).map(move |r| {
233             coop.made_progress();
234             r
235         })
236     }
237 }
238 
239 impl Future for Sleep {
240     type Output = ();
241 
poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output>242     fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
243         // `poll_elapsed` can return an error in two cases:
244         //
245         // - AtCapacity: this is a pathological case where far too many
246         //   sleep instances have been scheduled.
247         // - Shutdown: No timer has been setup, which is a mis-use error.
248         //
249         // Both cases are extremely rare, and pretty accurately fit into
250         // "logic errors", so we just panic in this case. A user couldn't
251         // really do much better if we passed the error onwards.
252         match ready!(self.as_mut().poll_elapsed(cx)) {
253             Ok(()) => Poll::Ready(()),
254             Err(e) => panic!("timer error: {}", e),
255         }
256     }
257 }
258