time: introduce sleep and sleep_until functions (#2826)

This commit is contained in:
Juan Alvarez
2020-10-01 09:24:33 +02:00
committed by GitHub
parent 971ed2c6df
commit 53ccfc1fd6
31 changed files with 152 additions and 153 deletions
+2 -2
View File
@@ -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;
@@ -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");
}
+2 -2
View File
@@ -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]
@@ -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;
});
}
+3 -3
View File
@@ -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()
@@ -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>;
+4 -4
View File
@@ -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();
/// });
///
@@ -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();
/// });
///
+1 -1
View File
@@ -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 }));
}
+1 -1
View File
@@ -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()
//!
+4 -4
View File
@@ -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! {
@@ -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! {
@@ -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! {
+4 -4
View File
@@ -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 ♫");
/// });
@@ -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;
/// # }
/// ```
///
@@ -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
/// }));
///
+3 -3
View File
@@ -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();
+3 -3
View File
@@ -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();
@@ -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! {
@@ -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();
+2 -2
View File
@@ -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() {
@@ -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;
/// }
/// }
/// ```
+1 -1
View File
@@ -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)
/// });
///
+9 -10
View File
@@ -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
@@ -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 {
@@ -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.
//
+5 -5
View File
@@ -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;
@@ -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,
@@ -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
@@ -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));
}
}
@@ -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)));
+2 -2
View File
@@ -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.
+6 -6
View File
@@ -50,12 +50,12 @@ impl Instant {
/// # Examples
///
/// ```
/// use tokio::time::{Duration, Instant, delay_for};
/// use tokio::time::{Duration, Instant, sleep};
///
/// #[tokio::main]
/// async fn main() {
/// let now = Instant::now();
/// delay_for(Duration::new(1, 0)).await;
/// sleep(Duration::new(1, 0)).await;
/// let new_now = Instant::now();
/// println!("{:?}", new_now.checked_duration_since(now));
/// println!("{:?}", now.checked_duration_since(new_now)); // None
@@ -71,12 +71,12 @@ impl Instant {
/// # Examples
///
/// ```
/// use tokio::time::{Duration, Instant, delay_for};
/// use tokio::time::{Duration, Instant, sleep};
///
/// #[tokio::main]
/// async fn main() {
/// let now = Instant::now();
/// delay_for(Duration::new(1, 0)).await;
/// sleep(Duration::new(1, 0)).await;
/// let new_now = Instant::now();
/// println!("{:?}", new_now.saturating_duration_since(now));
/// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
@@ -97,13 +97,13 @@ impl Instant {
/// # Examples
///
/// ```
/// use tokio::time::{Duration, Instant, delay_for};
/// use tokio::time::{Duration, Instant, sleep};
///
/// #[tokio::main]
/// async fn main() {
/// let instant = Instant::now();
/// let three_secs = Duration::from_secs(3);
/// delay_for(three_secs).await;
/// sleep(three_secs).await;
/// assert!(instant.elapsed() >= three_secs);
/// }
/// ```
+6 -6
View File
@@ -1,5 +1,5 @@
use crate::future::poll_fn;
use crate::time::{delay_until, Delay, Duration, Instant};
use crate::time::{sleep_until, Delay, Duration, Instant};
use std::future::Future;
use std::pin::Pin;
@@ -36,12 +36,12 @@ use std::task::{Context, Poll};
///
/// A simple example using `interval` to execute a task every two seconds.
///
/// The difference between `interval` and [`delay_for`] is that an `interval`
/// The difference between `interval` and [`sleep`] is that an `interval`
/// measures the time since the last tick, which means that `.tick().await`
/// may wait for a shorter time than the duration specified for the interval
/// if some time has passed between calls to `.tick().await`.
///
/// If the tick in the example below was replaced with [`delay_for`], the task
/// If the tick in the example below was replaced with [`sleep`], the task
/// would only be executed once every three seconds, and not every two
/// seconds.
///
@@ -50,7 +50,7 @@ use std::task::{Context, Poll};
///
/// async fn task_that_takes_a_second() {
/// println!("hello");
/// time::delay_for(time::Duration::from_secs(1)).await
/// time::sleep(time::Duration::from_secs(1)).await
/// }
///
/// #[tokio::main]
@@ -63,7 +63,7 @@ use std::task::{Context, Poll};
/// }
/// ```
///
/// [`delay_for`]: crate::time::delay_for()
/// [`sleep`]: crate::time::sleep()
pub fn interval(period: Duration) -> Interval {
assert!(period > Duration::new(0, 0), "`period` must be non-zero.");
@@ -101,7 +101,7 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval {
assert!(period > Duration::new(0, 0), "`period` must be non-zero.");
Interval {
delay: delay_until(start),
delay: sleep_until(start),
period,
}
}
+7 -7
View File
@@ -27,14 +27,14 @@
//! Wait 100ms and print "100 ms have elapsed"
//!
//! ```
//! use tokio::time::delay_for;
//! use tokio::time::sleep;
//!
//! use std::time::Duration;
//!
//!
//! #[tokio::main]
//! async fn main() {
//! delay_for(Duration::from_millis(100)).await;
//! sleep(Duration::from_millis(100)).await;
//! println!("100 ms have elapsed");
//! }
//! ```
@@ -61,12 +61,12 @@
//!
//! A simple example using [`interval`] to execute a task every two seconds.
//!
//! The difference between [`interval`] and [`delay_for`] is that an
//! The difference between [`interval`] and [`sleep`] is that an
//! [`interval`] measures the time since the last tick, which means that
//! `.tick().await` may wait for a shorter time than the duration specified
//! for the interval if some time has passed between calls to `.tick().await`.
//!
//! If the tick in the example below was replaced with [`delay_for`], the task
//! If the tick in the example below was replaced with [`sleep`], the task
//! would only be executed once every three seconds, and not every two
//! seconds.
//!
@@ -75,7 +75,7 @@
//!
//! async fn task_that_takes_a_second() {
//! println!("hello");
//! time::delay_for(time::Duration::from_secs(1)).await
//! time::sleep(time::Duration::from_secs(1)).await
//! }
//!
//! #[tokio::main]
@@ -88,7 +88,7 @@
//! }
//! ```
//!
//! [`delay_for`]: crate::time::delay_for()
//! [`sleep`]: crate::time::sleep()
//! [`interval`]: crate::time::interval()
mod clock;
@@ -101,7 +101,7 @@ pub mod delay_queue;
pub use delay_queue::DelayQueue;
mod delay;
pub use delay::{delay_for, delay_until, Delay};
pub use delay::{sleep, sleep_until, Delay};
pub(crate) mod driver;
+1 -1
View File
@@ -18,5 +18,5 @@ fn registration_is_send_and_sync() {
#[should_panic]
fn delay_is_eager() {
let when = Instant::now() + Duration::from_millis(100);
let _ = time::delay_until(when);
let _ = time::sleep_until(when);
}
+2 -2
View File
@@ -4,7 +4,7 @@
//!
//! [`Timeout`]: struct@Timeout
use crate::time::{delay_until, Delay, Duration, Instant};
use crate::time::{sleep_until, Delay, Duration, Instant};
use pin_project_lite::pin_project;
use std::fmt;
@@ -92,7 +92,7 @@ pub fn timeout_at<T>(deadline: Instant, future: T) -> Timeout<T>
where
T: Future,
{
let delay = delay_until(deadline);
let delay = sleep_until(deadline);
Timeout {
value: future,
+2 -2
View File
@@ -243,8 +243,8 @@ async_assert_fn!(tokio::task::LocalSet::run_until(_, BoxFutureSync<()>): !Send &
assert_value!(tokio::task::LocalSet: !Send & !Sync);
async_assert_fn!(tokio::time::advance(Duration): Send & Sync);
async_assert_fn!(tokio::time::delay_for(Duration): Send & Sync);
async_assert_fn!(tokio::time::delay_until(Instant): Send & Sync);
async_assert_fn!(tokio::time::sleep(Duration): Send & Sync);
async_assert_fn!(tokio::time::sleep_until(Instant): Send & Sync);
async_assert_fn!(tokio::time::timeout(Duration, BoxFutureSync<()>): Send & Sync);
async_assert_fn!(tokio::time::timeout(Duration, BoxFutureSend<()>): Send & !Sync);
async_assert_fn!(tokio::time::timeout(Duration, BoxFuture<()>): !Send & !Sync);
+2 -2
View File
@@ -359,7 +359,7 @@ async fn join_with_select() {
async fn use_future_in_if_condition() {
use tokio::time::{self, Duration};
let mut delay = time::delay_for(Duration::from_millis(50));
let mut delay = time::sleep(Duration::from_millis(50));
tokio::select! {
_ = &mut delay, if !delay.is_elapsed() => {
@@ -459,7 +459,7 @@ async fn async_noop() {}
async fn async_never() -> ! {
use tokio::time::Duration;
loop {
tokio::time::delay_for(Duration::from_millis(10)).await;
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ async fn issue_2174() {
});
// Sleep enough time so that the child process's stdin's buffer fills.
time::delay_for(Duration::from_secs(1)).await;
time::sleep(Duration::from_secs(1)).await;
// Kill the child process.
child.kill().await.unwrap();
+2 -2
View File
@@ -5,7 +5,7 @@ use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::delay_for;
use tokio::time::sleep;
use tokio_test::assert_ok;
#[tokio::test]
@@ -30,7 +30,7 @@ async fn kill_on_drop() {
.spawn()
.unwrap();
delay_for(Duration::from_secs(2)).await;
sleep(Duration::from_secs(2)).await;
let mut out = child.stdout.take().unwrap();
drop(child);
+10 -10
View File
@@ -437,7 +437,7 @@ rt_test! {
let dur = Duration::from_millis(50);
rt.block_on(async move {
time::delay_for(dur).await;
time::sleep(dur).await;
});
assert!(now.elapsed() >= dur);
@@ -454,7 +454,7 @@ rt_test! {
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
time::delay_for(dur).await;
time::sleep(dur).await;
assert_ok!(tx.send(()));
});
@@ -526,7 +526,7 @@ rt_test! {
// use the futures' block_on fn to make sure we aren't setting
// any Tokio context
futures::executor::block_on(async {
tokio::time::delay_for(dur).await;
tokio::time::sleep(dur).await;
});
assert!(now.elapsed() >= dur);
@@ -588,7 +588,7 @@ rt_test! {
let jh1 = thread::spawn(move || {
rt.block_on(async move {
rx2.await.unwrap();
time::delay_for(Duration::from_millis(5)).await;
time::sleep(Duration::from_millis(5)).await;
tx1.send(()).unwrap();
});
});
@@ -596,9 +596,9 @@ rt_test! {
let jh2 = thread::spawn(move || {
rt2.block_on(async move {
tx2.send(()).unwrap();
time::delay_for(Duration::from_millis(5)).await;
time::sleep(Duration::from_millis(5)).await;
rx1.await.unwrap();
time::delay_for(Duration::from_millis(5)).await;
time::sleep(Duration::from_millis(5)).await;
});
});
@@ -850,11 +850,11 @@ rt_test! {
let buf = [0];
loop {
send_half.send_to(&buf, &addr).await.unwrap();
tokio::time::delay_for(Duration::from_millis(1)).await;
tokio::time::sleep(Duration::from_millis(1)).await;
}
});
tokio::time::delay_for(Duration::from_millis(5)).await;
tokio::time::sleep(Duration::from_millis(5)).await;
});
}
}
@@ -881,7 +881,7 @@ rt_test! {
let runtime = rt();
runtime.block_on(async move {
tokio::time::delay_for(std::time::Duration::from_millis(100)).await;
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
});
Arc::try_unwrap(runtime).unwrap().shutdown_timeout(Duration::from_secs(10_000));
@@ -1006,7 +1006,7 @@ rt_test! {
}).collect::<Vec<_>>();
// Hope that all the tasks complete...
time::delay_for(Duration::from_millis(100)).await;
time::sleep(Duration::from_millis(100)).await;
poll_fn(|cx| {
// At least one task should not be ready
+2 -2
View File
@@ -1,14 +1,14 @@
#![cfg(feature = "full")]
use tokio::stream::{self, StreamExt};
use tokio::time::{self, delay_for, Duration};
use tokio::time::{self, sleep, Duration};
use tokio_test::*;
use futures::StreamExt as _;
async fn maybe_delay(idx: i32) -> i32 {
if idx % 2 == 0 {
delay_for(ms(200)).await;
sleep(ms(200)).await;
}
idx
}
+1 -1
View File
@@ -16,7 +16,7 @@ async fn local() {
assert_eq!(*v, 2);
});
tokio::time::delay_for(std::time::Duration::from_millis(10)).await;
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
assert_eq!(REQ_ID.get(), 2);
}));
+8 -8
View File
@@ -62,11 +62,11 @@ async fn localset_future_timers() {
let local = LocalSet::new();
local.spawn_local(async move {
time::delay_for(Duration::from_millis(10)).await;
time::sleep(Duration::from_millis(10)).await;
RAN1.store(true, Ordering::SeqCst);
});
local.spawn_local(async move {
time::delay_for(Duration::from_millis(20)).await;
time::sleep(Duration::from_millis(20)).await;
RAN2.store(true, Ordering::SeqCst);
});
local.await;
@@ -114,7 +114,7 @@ async fn local_threadpool_timer() {
assert!(ON_RT_THREAD.with(|cell| cell.get()));
let join = task::spawn_local(async move {
assert!(ON_RT_THREAD.with(|cell| cell.get()));
time::delay_for(Duration::from_millis(10)).await;
time::sleep(Duration::from_millis(10)).await;
assert!(ON_RT_THREAD.with(|cell| cell.get()));
});
join.await.unwrap();
@@ -299,7 +299,7 @@ fn drop_cancels_tasks() {
started_tx.send(()).unwrap();
loop {
time::delay_for(Duration::from_secs(3600)).await;
time::sleep(Duration::from_secs(3600)).await;
}
});
@@ -367,7 +367,7 @@ fn drop_cancels_remote_tasks() {
let local = LocalSet::new();
local.spawn_local(async move { while rx.recv().await.is_some() {} });
local.block_on(&rt, async {
time::delay_for(Duration::from_millis(1)).await;
time::sleep(Duration::from_millis(1)).await;
});
drop(tx);
@@ -415,7 +415,7 @@ async fn local_tasks_are_polled_after_tick() {
.run_until(async {
let task2 = task::spawn(async move {
// Wait a bit
time::delay_for(Duration::from_millis(100)).await;
time::sleep(Duration::from_millis(100)).await;
let mut oneshots = Vec::with_capacity(EXPECTED);
@@ -426,13 +426,13 @@ async fn local_tasks_are_polled_after_tick() {
tx.send(oneshot_rx).unwrap();
}
time::delay_for(Duration::from_millis(100)).await;
time::sleep(Duration::from_millis(100)).await;
for tx in oneshots.drain(..) {
tx.send(()).unwrap();
}
time::delay_for(Duration::from_millis(300)).await;
time::sleep(Duration::from_millis(300)).await;
let rx1 = RX1.load(SeqCst);
let rx2 = RX2.load(SeqCst);
println!("EXPECT = {}; RX1 = {}; RX2 = {}", EXPECTED, rx1, rx2);
+16 -16
View File
@@ -26,7 +26,7 @@ async fn immediate_delay() {
let now = Instant::now();
// Ready!
time::delay_until(now).await;
time::sleep_until(now).await;
assert_elapsed!(now, 0);
}
@@ -37,7 +37,7 @@ async fn delayed_delay_level_0() {
for &i in &[1, 10, 60] {
let now = Instant::now();
time::delay_until(now + ms(i)).await;
time::sleep_until(now + ms(i)).await;
assert_elapsed!(now, i);
}
@@ -51,7 +51,7 @@ async fn sub_ms_delayed_delay() {
let now = Instant::now();
let deadline = now + ms(1) + Duration::new(0, 1);
time::delay_until(deadline).await;
time::sleep_until(deadline).await;
assert_elapsed!(now, 1);
}
@@ -61,10 +61,10 @@ async fn sub_ms_delayed_delay() {
async fn delayed_delay_wrapping_level_0() {
time::pause();
time::delay_for(ms(5)).await;
time::sleep(ms(5)).await;
let now = Instant::now();
time::delay_until(now + ms(60)).await;
time::sleep_until(now + ms(60)).await;
assert_elapsed!(now, 60);
}
@@ -75,7 +75,7 @@ async fn reset_future_delay_before_fire() {
let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100)));
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut delay = delay.into_inner();
@@ -92,7 +92,7 @@ async fn reset_past_delay_before_turn() {
let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100)));
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut delay = delay.into_inner();
@@ -109,12 +109,12 @@ async fn reset_past_delay_before_fire() {
let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100)));
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut delay = delay.into_inner();
time::delay_for(ms(10)).await;
time::sleep(ms(10)).await;
delay.reset(now + ms(80));
delay.await;
@@ -127,7 +127,7 @@ async fn reset_future_delay_after_fire() {
time::pause();
let now = Instant::now();
let mut delay = time::delay_until(now + ms(100));
let mut delay = time::sleep_until(now + ms(100));
(&mut delay).await;
assert_elapsed!(now, 100);
@@ -143,10 +143,10 @@ async fn reset_delay_to_past() {
let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100)));
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
time::delay_for(ms(50)).await;
time::sleep(ms(50)).await;
assert!(!delay.is_woken());
@@ -164,7 +164,7 @@ fn creating_delay_outside_of_context() {
// This creates a delay outside of the context of a mock timer. This tests
// that it will panic.
let _fut = time::delay_until(now + ms(500));
let _fut = time::sleep_until(now + ms(500));
}
#[should_panic]
@@ -172,7 +172,7 @@ fn creating_delay_outside_of_context() {
async fn greater_than_max() {
const YR_5: u64 = 5 * 365 * 24 * 60 * 60 * 1000;
time::delay_until(Instant::now() + ms(YR_5)).await;
time::sleep_until(Instant::now() + ms(YR_5)).await;
}
const NUM_LEVELS: usize = 6;
@@ -182,13 +182,13 @@ const MAX_DURATION: u64 = (1 << (6 * NUM_LEVELS)) - 1;
#[tokio::test]
async fn exactly_max() {
// TODO: this should not panic but `time::ms()` is acting up
time::delay_for(ms(MAX_DURATION)).await;
time::sleep(ms(MAX_DURATION)).await;
}
#[tokio::test]
async fn no_out_of_bounds_close_to_max() {
time::pause();
time::delay_for(ms(MAX_DURATION - 1)).await;
time::sleep(ms(MAX_DURATION - 1)).await;
}
fn ms(n: u64) -> Duration {
+37 -37
View File
@@ -2,7 +2,7 @@
#![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
use tokio::time::{self, delay_for, DelayQueue, Duration, Instant};
use tokio::time::{self, sleep, DelayQueue, Duration, Instant};
use tokio_test::{assert_ok, assert_pending, assert_ready, task};
macro_rules! poll {
@@ -28,7 +28,7 @@ async fn single_immediate_delay() {
let _key = queue.insert_at("foo", Instant::now());
// Advance time by 1ms to handle thee rounding
delay_for(ms(1)).await;
sleep(ms(1)).await;
assert_ready_ok!(poll!(queue));
@@ -46,7 +46,7 @@ async fn multi_immediate_delays() {
let _k = queue.insert_at("2", Instant::now());
let _k = queue.insert_at("3", Instant::now());
delay_for(ms(1)).await;
sleep(ms(1)).await;
let mut res = vec![];
@@ -74,11 +74,11 @@ async fn single_short_delay() {
assert_pending!(poll!(queue));
delay_for(ms(1)).await;
sleep(ms(1)).await;
assert!(!queue.is_woken());
delay_for(ms(5)).await;
sleep(ms(5)).await;
assert!(queue.is_woken());
@@ -107,7 +107,7 @@ async fn multi_delay_at_start() {
assert!(!queue.is_woken());
for elapsed in 0..1200 {
delay_for(ms(1)).await;
sleep(ms(1)).await;
let elapsed = elapsed + 1;
if delays.contains(&elapsed) {
@@ -130,7 +130,7 @@ async fn insert_in_past_fires_immediately() {
let mut queue = task::spawn(DelayQueue::new());
let now = Instant::now();
delay_for(ms(10)).await;
sleep(ms(10)).await;
queue.insert_at("foo", now);
@@ -150,7 +150,7 @@ async fn remove_entry() {
let entry = queue.remove(&key);
assert_eq!(entry.into_inner(), "foo");
delay_for(ms(10)).await;
sleep(ms(10)).await;
let entry = assert_ready!(poll!(queue));
assert!(entry.is_none());
@@ -166,19 +166,19 @@ async fn reset_entry() {
let key = queue.insert_at("foo", now + ms(5));
assert_pending!(poll!(queue));
delay_for(ms(1)).await;
sleep(ms(1)).await;
queue.reset_at(&key, now + ms(10));
assert_pending!(poll!(queue));
delay_for(ms(7)).await;
sleep(ms(7)).await;
assert!(!queue.is_woken());
assert_pending!(poll!(queue));
delay_for(ms(3)).await;
sleep(ms(3)).await;
assert!(queue.is_woken());
@@ -197,16 +197,16 @@ async fn reset_much_later() {
let mut queue = task::spawn(DelayQueue::new());
let now = Instant::now();
delay_for(ms(1)).await;
sleep(ms(1)).await;
let key = queue.insert_at("foo", now + ms(200));
assert_pending!(poll!(queue));
delay_for(ms(3)).await;
sleep(ms(3)).await;
queue.reset_at(&key, now + ms(5));
delay_for(ms(20)).await;
sleep(ms(20)).await;
assert!(queue.is_woken());
}
@@ -219,21 +219,21 @@ async fn reset_twice() {
let mut queue = task::spawn(DelayQueue::new());
let now = Instant::now();
delay_for(ms(1)).await;
sleep(ms(1)).await;
let key = queue.insert_at("foo", now + ms(200));
assert_pending!(poll!(queue));
delay_for(ms(3)).await;
sleep(ms(3)).await;
queue.reset_at(&key, now + ms(50));
delay_for(ms(20)).await;
sleep(ms(20)).await;
queue.reset_at(&key, now + ms(40));
delay_for(ms(20)).await;
sleep(ms(20)).await;
assert!(queue.is_woken());
}
@@ -246,7 +246,7 @@ async fn remove_expired_item() {
let now = Instant::now();
delay_for(ms(10)).await;
sleep(ms(10)).await;
let key = queue.insert_at("foo", now);
@@ -272,7 +272,7 @@ async fn expires_before_last_insert() {
assert_pending!(poll!(queue));
delay_for(ms(600)).await;
sleep(ms(600)).await;
assert!(queue.is_woken());
@@ -297,18 +297,18 @@ async fn multi_reset() {
queue.reset_at(&two, now + ms(350));
queue.reset_at(&one, now + ms(400));
delay_for(ms(310)).await;
sleep(ms(310)).await;
assert_pending!(poll!(queue));
delay_for(ms(50)).await;
sleep(ms(50)).await;
let entry = assert_ready_ok!(poll!(queue));
assert_eq!(*entry.get_ref(), "two");
assert_pending!(poll!(queue));
delay_for(ms(50)).await;
sleep(ms(50)).await;
let entry = assert_ready_ok!(poll!(queue));
assert_eq!(*entry.get_ref(), "one");
@@ -332,7 +332,7 @@ async fn expire_first_key_when_reset_to_expire_earlier() {
queue.reset_at(&one, now + ms(100));
delay_for(ms(100)).await;
sleep(ms(100)).await;
assert!(queue.is_woken());
@@ -355,7 +355,7 @@ async fn expire_second_key_when_reset_to_expire_earlier() {
queue.reset_at(&two, now + ms(100));
delay_for(ms(100)).await;
sleep(ms(100)).await;
assert!(queue.is_woken());
@@ -377,7 +377,7 @@ async fn reset_first_expiring_item_to_expire_later() {
assert_pending!(poll!(queue));
queue.reset_at(&one, now + ms(300));
delay_for(ms(250)).await;
sleep(ms(250)).await;
assert!(queue.is_woken());
@@ -399,11 +399,11 @@ async fn insert_before_first_after_poll() {
let _two = queue.insert_at("two", now + ms(100));
delay_for(ms(99)).await;
sleep(ms(99)).await;
assert!(!queue.is_woken());
delay_for(ms(1)).await;
sleep(ms(1)).await;
assert!(queue.is_woken());
@@ -425,7 +425,7 @@ async fn insert_after_ready_poll() {
assert_pending!(poll!(queue));
delay_for(ms(100)).await;
sleep(ms(100)).await;
assert!(queue.is_woken());
@@ -456,7 +456,7 @@ async fn reset_later_after_slot_starts() {
assert_pending!(poll!(queue));
delay_for(ms(80)).await;
sleep(ms(80)).await;
assert!(!queue.is_woken());
@@ -471,10 +471,10 @@ async fn reset_later_after_slot_starts() {
assert_pending!(poll!(queue));
delay_for(ms(39)).await;
sleep(ms(39)).await;
assert!(!queue.is_woken());
delay_for(ms(1)).await;
sleep(ms(1)).await;
assert!(queue.is_woken());
let entry = assert_ready_ok!(poll!(queue)).into_inner();
@@ -494,7 +494,7 @@ async fn reset_inserted_expired() {
assert_eq!(1, queue.len());
delay_for(ms(200)).await;
sleep(ms(200)).await;
let entry = assert_ready_ok!(poll!(queue)).into_inner();
assert_eq!(entry, "foo");
@@ -514,7 +514,7 @@ async fn reset_earlier_after_slot_starts() {
assert_pending!(poll!(queue));
delay_for(ms(80)).await;
sleep(ms(80)).await;
assert!(!queue.is_woken());
@@ -529,10 +529,10 @@ async fn reset_earlier_after_slot_starts() {
assert_pending!(poll!(queue));
delay_for(ms(39)).await;
sleep(ms(39)).await;
assert!(!queue.is_woken());
delay_for(ms(1)).await;
sleep(ms(1)).await;
assert!(queue.is_woken());
let entry = assert_ready_ok!(poll!(queue)).into_inner();
@@ -551,7 +551,7 @@ async fn insert_in_past_after_poll_fires_immediately() {
assert_pending!(poll!(queue));
delay_for(ms(80)).await;
sleep(ms(80)).await;
assert!(!queue.is_woken());
queue.insert_at("bar", now + ms(40));
+3 -3
View File
@@ -15,7 +15,7 @@ fn timer_with_threaded_runtime() {
rt.spawn(async move {
let when = Instant::now() + Duration::from_millis(100);
delay_until(when).await;
sleep_until(when).await;
assert!(Instant::now() >= when);
tx.send(()).unwrap();
@@ -38,7 +38,7 @@ fn timer_with_basic_scheduler() {
rt.block_on(async move {
let when = Instant::now() + Duration::from_millis(100);
delay_until(when).await;
sleep_until(when).await;
assert!(Instant::now() >= when);
tx.send(()).unwrap();
@@ -72,7 +72,7 @@ async fn starving() {
}
let when = Instant::now() + Duration::from_millis(20);
let starve = Starve(delay_until(when), 0);
let starve = Starve(sleep_until(when), 0);
starve.await;
assert!(Instant::now() >= when);