Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

time: introduce sleep and sleep_until functions #2826

Merged
merged 5 commits into from Oct 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions tokio-test/src/io.rs
Expand Up @@ -365,7 +365,7 @@ impl AsyncRead for Mock {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
if let Some(rem) = self.inner.remaining_wait() {
let until = Instant::now() + rem;
self.inner.sleep = Some(time::delay_until(until));
self.inner.sleep = Some(time::sleep_until(until));
} else {
self.inner.read_wait = Some(cx.waker().clone());
return Poll::Pending;
Expand Down Expand Up @@ -410,7 +410,7 @@ impl AsyncWrite for Mock {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
if let Some(rem) = self.inner.remaining_wait() {
let until = Instant::now() + rem;
self.inner.sleep = Some(time::delay_until(until));
self.inner.sleep = Some(time::sleep_until(until));
} else {
panic!("unexpected WouldBlock");
}
Expand Down
4 changes: 2 additions & 2 deletions tokio-test/tests/block_on.rs
@@ -1,6 +1,6 @@
#![warn(rust_2018_idioms)]

use tokio::time::{delay_until, Duration, Instant};
use tokio::time::{sleep_until, Duration, Instant};
use tokio_test::block_on;

#[test]
Expand All @@ -22,6 +22,6 @@ fn test_delay() {
let deadline = Instant::now() + Duration::from_millis(100);

block_on(async {
delay_until(deadline).await;
sleep_until(deadline).await;
});
}
6 changes: 3 additions & 3 deletions tokio-util/src/context.rs
Expand Up @@ -46,7 +46,7 @@ pub trait RuntimeExt {
///
/// ```no_run
/// use tokio_util::context::RuntimeExt;
/// use tokio::time::{delay_for, Duration};
/// use tokio::time::{sleep, Duration};
///
/// let rt = tokio::runtime::Builder::new()
/// .threaded_scheduler()
Expand All @@ -57,11 +57,11 @@ pub trait RuntimeExt {
/// .threaded_scheduler()
/// .build().unwrap();
///
/// let fut = delay_for(Duration::from_millis(2));
/// let fut = sleep(Duration::from_millis(2));
///
/// rt.block_on(
/// rt2
/// .wrap(async { delay_for(Duration::from_millis(2)).await }),
/// .wrap(async { sleep(Duration::from_millis(2)).await }),
/// );
///```
fn wrap<F: Future>(&self, fut: F) -> TokioContext<'_, F>;
Expand Down
8 changes: 4 additions & 4 deletions tokio-util/src/sync/cancellation_token.rs
Expand Up @@ -37,14 +37,14 @@ use core::task::{Context, Poll, Waker};
/// // The token was cancelled
/// 5
/// }
/// _ = tokio::time::delay_for(std::time::Duration::from_secs(9999)) => {
/// _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
/// 99
/// }
/// }
/// });
///
/// tokio::spawn(async move {
/// tokio::time::delay_for(std::time::Duration::from_millis(10)).await;
/// tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// token.cancel();
/// });
///
Expand Down Expand Up @@ -185,14 +185,14 @@ impl CancellationToken {
/// // The token was cancelled
/// 5
/// }
/// _ = tokio::time::delay_for(std::time::Duration::from_secs(9999)) => {
/// _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
/// 99
/// }
/// }
/// });
///
/// tokio::spawn(async move {
/// tokio::time::delay_for(std::time::Duration::from_millis(10)).await;
/// tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// token.cancel();
/// });
///
Expand Down
2 changes: 1 addition & 1 deletion tokio-util/tests/context.rs
Expand Up @@ -21,5 +21,5 @@ fn tokio_context_with_another_runtime() {

// Without the `HandleExt.wrap()` there would be a panic because there is
// no timer running, since it would be referencing runtime r1.
let _ = rt1.block_on(rt2.wrap(async move { delay_for(Duration::from_millis(2)).await }));
let _ = rt1.block_on(rt2.wrap(async move { sleep(Duration::from_millis(2)).await }));
}
2 changes: 1 addition & 1 deletion tokio/src/lib.rs
Expand Up @@ -189,7 +189,7 @@
//! In order to use `tokio::time`, the "time" feature flag must be enabled.
//!
//! [`tokio::time`]: crate::time
//! [delay]: crate::time::delay_for()
//! [delay]: crate::time::sleep()
//! [interval]: crate::time::interval()
//! [timeout]: crate::time::timeout()
//!
Expand Down
8 changes: 4 additions & 4 deletions tokio/src/macros/select.rs
Expand Up @@ -76,7 +76,7 @@
///
/// #[tokio::main]
/// async fn main() {
/// let mut delay = time::delay_for(Duration::from_millis(50));
/// let mut delay = time::sleep(Duration::from_millis(50));
///
/// while !delay.is_elapsed() {
/// tokio::select! {
Expand All @@ -103,13 +103,13 @@
/// use tokio::time::{self, Duration};
///
/// async fn some_async_work() {
/// # time::delay_for(Duration::from_millis(10)).await;
/// # time::sleep(Duration::from_millis(10)).await;
/// // do work
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let mut delay = time::delay_for(Duration::from_millis(50));
/// let mut delay = time::sleep(Duration::from_millis(50));
///
/// loop {
/// tokio::select! {
Expand Down Expand Up @@ -226,7 +226,7 @@
/// #[tokio::main]
/// async fn main() {
/// let mut stream = stream::iter(vec![1, 2, 3]);
/// let mut delay = time::delay_for(Duration::from_secs(1));
/// let mut delay = time::sleep(Duration::from_secs(1));
///
/// loop {
/// tokio::select! {
Expand Down
8 changes: 4 additions & 4 deletions tokio/src/runtime/task/join.rs
Expand Up @@ -121,7 +121,7 @@ doc_rt_core! {
/// let original_task = task::spawn(async {
/// let _detached_task = task::spawn(async {
/// // Here we sleep to make sure that the first task returns before.
/// time::delay_for(Duration::from_millis(10)).await;
/// time::sleep(Duration::from_millis(10)).await;
/// // This will be called, even though the JoinHandle is dropped.
/// println!("♫ Still alive ♫");
/// });
Expand All @@ -133,7 +133,7 @@ doc_rt_core! {
/// // We make sure that the new task has time to run, before the main
/// // task returns.
///
/// time::delay_for(Duration::from_millis(1000)).await;
/// time::sleep(Duration::from_millis(1000)).await;
/// # }
/// ```
///
Expand Down Expand Up @@ -172,12 +172,12 @@ impl<T> JoinHandle<T> {
/// let mut handles = Vec::new();
///
/// handles.push(tokio::spawn(async {
/// time::delay_for(time::Duration::from_secs(10)).await;
/// time::sleep(time::Duration::from_secs(10)).await;
/// true
/// }));
///
/// handles.push(tokio::spawn(async {
/// time::delay_for(time::Duration::from_secs(10)).await;
/// time::sleep(time::Duration::from_secs(10)).await;
/// false
/// }));
///
Expand Down
6 changes: 3 additions & 3 deletions tokio/src/stream/mod.rs
Expand Up @@ -281,18 +281,18 @@ pub trait StreamExt: Stream {
/// tx1.send(2).await.unwrap();
///
/// // Let the other task send values
/// time::delay_for(Duration::from_millis(20)).await;
/// time::sleep(Duration::from_millis(20)).await;
///
/// tx1.send(4).await.unwrap();
/// });
///
/// tokio::spawn(async move {
/// // Wait for the first task to send values
/// time::delay_for(Duration::from_millis(5)).await;
/// time::sleep(Duration::from_millis(5)).await;
///
/// tx2.send(3).await.unwrap();
///
/// time::delay_for(Duration::from_millis(25)).await;
/// time::sleep(Duration::from_millis(25)).await;
///
/// // Send the final value
/// tx2.send(5).await.unwrap();
Expand Down
6 changes: 3 additions & 3 deletions tokio/src/sync/mod.rs
Expand Up @@ -322,7 +322,7 @@
//! tokio::spawn(async move {
//! loop {
//! // Wait 10 seconds between checks
//! time::delay_for(Duration::from_secs(10)).await;
//! time::sleep(Duration::from_secs(10)).await;
//!
//! // Load the configuration file
//! let new_config = Config::load_from_file().await.unwrap();
Expand Down Expand Up @@ -359,7 +359,7 @@
//! let mut conf = rx.borrow().clone();
//!
//! let mut op_start = Instant::now();
//! let mut delay = time::delay_until(op_start + conf.timeout);
//! let mut delay = time::sleep_until(op_start + conf.timeout);
//!
//! loop {
//! tokio::select! {
Expand All @@ -371,7 +371,7 @@
//! op_start = Instant::now();
//!
//! // Restart the timeout
//! delay = time::delay_until(op_start + conf.timeout);
//! delay = time::sleep_until(op_start + conf.timeout);
//! }
//! _ = rx.changed() => {
//! conf = rx.borrow().clone();
Expand Down
4 changes: 2 additions & 2 deletions tokio/src/sync/mpsc/bounded.rs
Expand Up @@ -449,7 +449,7 @@ impl<T> Sender<T> {
///
/// ```rust
/// use tokio::sync::mpsc;
/// use tokio::time::{delay_for, Duration};
/// use tokio::time::{sleep, Duration};
///
/// #[tokio::main]
/// async fn main() {
Expand All @@ -466,7 +466,7 @@ impl<T> Sender<T> {
///
/// while let Some(i) = rx.recv().await {
/// println!("got = {}", i);
/// delay_for(Duration::from_millis(200)).await;
/// sleep(Duration::from_millis(200)).await;
/// }
/// }
/// ```
Expand Down
2 changes: 1 addition & 1 deletion tokio/src/task/local.rs
Expand Up @@ -95,7 +95,7 @@ cfg_rt_util! {
/// });
///
/// local.spawn_local(async move {
/// time::delay_for(time::Duration::from_millis(100)).await;
/// time::sleep(time::Duration::from_millis(100)).await;
/// println!("goodbye {}", unsend_data)
/// });
///
Expand Down
19 changes: 9 additions & 10 deletions tokio/src/time/delay.rs
Expand Up @@ -15,14 +15,14 @@ use std::task::{self, Poll};
///
/// Canceling a delay is done by dropping the returned future. No additional
/// cleanup work is required.
pub fn delay_until(deadline: Instant) -> Delay {
pub fn sleep_until(deadline: Instant) -> Delay {
let registration = Registration::new(deadline, Duration::from_millis(0));
Delay { registration }
}

/// Waits until `duration` has elapsed.
///
/// Equivalent to `delay_until(Instant::now() + duration)`. An asynchronous
/// Equivalent to `sleep_until(Instant::now() + duration)`. An asynchronous
/// analog to `std::thread::sleep`.
///
/// No work is performed while awaiting on the delay to complete. The delay
Expand All @@ -41,23 +41,22 @@ pub fn delay_until(deadline: Instant) -> Delay {
/// Wait 100ms and print "100 ms have elapsed".
///
/// ```
/// use tokio::time::{delay_for, Duration};
/// use tokio::time::{sleep, Duration};
///
/// #[tokio::main]
/// async fn main() {
/// delay_for(Duration::from_millis(100)).await;
/// sleep(Duration::from_millis(100)).await;
/// println!("100 ms have elapsed");
/// }
/// ```
///
/// [`interval`]: crate::time::interval()
#[cfg_attr(docsrs, doc(alias = "sleep"))]
pub fn delay_for(duration: Duration) -> Delay {
delay_until(Instant::now() + duration)
pub fn sleep(duration: Duration) -> Delay {
sleep_until(Instant::now() + duration)
}

/// Future returned by [`delay_until`](delay_until) and
/// [`delay_for`](delay_for).
/// Future returned by [`sleep`](sleep) and
/// [`sleep_until`](sleep_until).
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Delay {
Expand Down Expand Up @@ -103,7 +102,7 @@ impl Future for Delay {
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
// `poll_elapsed` can return an error in two cases:
//
// - AtCapacity: this is a pathlogical case where far too many
// - AtCapacity: this is a pathological case where far too many
// delays have been scheduled.
// - Shutdown: No timer has been setup, which is a mis-use error.
//
Expand Down
10 changes: 5 additions & 5 deletions tokio/src/time/delay_queue.rs
Expand Up @@ -5,7 +5,7 @@
//! [`DelayQueue`]: struct@DelayQueue

use crate::time::wheel::{self, Wheel};
use crate::time::{delay_until, Delay, Duration, Error, Instant};
use crate::time::{sleep_until, Delay, Duration, Error, Instant};

use slab::Slab;
use std::cmp;
Expand Down Expand Up @@ -51,7 +51,7 @@ use std::task::{self, Poll};
/// # Implementation
///
/// The [`DelayQueue`] is backed by a separate instance of the same timer wheel used internally by
/// Tokio's standalone timer utilities such as [`delay_for`]. Because of this, it offers the same
/// Tokio's standalone timer utilities such as [`sleep`]. Because of this, it offers the same
/// performance and scalability benefits.
///
/// State associated with each entry is stored in a [`slab`]. This amortizes the cost of allocation,
Expand Down Expand Up @@ -118,7 +118,7 @@ use std::task::{self, Poll};
/// [`poll_expired`]: method@Self::poll_expired
/// [`Stream::poll_expired`]: method@Self::poll_expired
/// [`DelayQueue`]: struct@DelayQueue
/// [`delay_for`]: fn@super::delay_for
/// [`sleep`]: fn@super::sleep
/// [`slab`]: slab
/// [`capacity`]: method@Self::capacity
/// [`reserve`]: method@Self::reserve
Expand Down Expand Up @@ -330,7 +330,7 @@ impl<T> DelayQueue<T> {
if let Some(ref mut delay) = &mut self.delay {
delay.reset(delay_time);
} else {
self.delay = Some(delay_until(delay_time));
self.delay = Some(sleep_until(delay_time));
}
}

Expand Down Expand Up @@ -734,7 +734,7 @@ impl<T> DelayQueue<T> {
// We poll the wheel to get the next value out before finding the next deadline.
let wheel_idx = self.wheel.poll(&mut self.poll, &mut self.slab);

self.delay = self.next_deadline().map(delay_until);
self.delay = self.next_deadline().map(sleep_until);

if let Some(idx) = wheel_idx {
return Poll::Ready(Some(Ok(idx)));
Expand Down
4 changes: 2 additions & 2 deletions tokio/src/time/driver/handle.rs
Expand Up @@ -25,9 +25,9 @@ impl Handle {
/// `Builder::enable_all()` are not included in the builder.
///
/// It can also panic whenever a timer is created outside of a Tokio
/// runtime. That is why `rt.block_on(delay_for(...))` will panic,
/// runtime. That is why `rt.block_on(sleep(...))` will panic,
/// since the function is executed outside of the runtime.
/// Whereas `rt.block_on(async {delay_for(...).await})` doesn't
/// Whereas `rt.block_on(async {sleep(...).await})` doesn't
/// panic. And this is because wrapping the function on an async makes it
/// lazy, and so gets executed inside the runtime successfuly without
/// panicking.
Expand Down