actix_rt::time

Function sleep

pub fn sleep(duration: Duration) -> Sleep 
Expand description

Waits until duration has elapsed.

Equivalent to sleep_until(Instant::now() + duration). An asynchronous analog to std::thread::sleep.

No work is performed while awaiting on the sleep future to complete. Sleep operates at millisecond granularity and should not be used for tasks that require high-resolution timers. The implementation is platform specific, and some platforms (specifically Windows) will provide timers with a larger resolution than 1 ms.

To run something regularly on a schedule, see interval.

The maximum duration for a sleep is 68719476734 milliseconds (approximately 2.2 years).

§Cancellation

Canceling a sleep instance is done by dropping the returned future. No additional cleanup work is required.

§Examples

Wait 100ms and print “100 ms have elapsed”.

use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    sleep(Duration::from_millis(100)).await;
    println!("100 ms have elapsed");
}

See the documentation for the Sleep type for more examples.

§Panics

This function panics if there is no current timer set.

It can be triggered when Builder::enable_time or 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(sleep(...)) will panic, since the function is executed outside of the runtime. 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 successfully without panicking.