Skip to main content

pause

Function pause 

Source
pub fn pause()
Available on crate features time and test-util only.
Expand description

Pauses time.

The current value of Instant::now() is saved and all subsequent calls to Instant::now() will return the saved value. The saved value can be changed by advance or by the time auto-advancing once the runtime has no work to do. This only affects the Instant type in Tokio, and the Instant in std continues to work as normal.

Pausing time requires the current_thread Tokio runtime. This is the default runtime used by #[tokio::test]. The runtime can be initialized with time in a paused state using the Builder::start_paused method.

For cases where time is immediately paused, it is better to pause the time using the main or test macro:

#[tokio::main(flavor = "current_thread", start_paused = true)]
async fn main() {
   println!("Hello world");
}

§Panics

Panics if time is already frozen or if called from outside of a current_thread Tokio runtime.

§Auto-advance

If time is paused and the runtime has no work to do, the clock is auto-advanced to the next pending timer. This means that Sleep or other timer-backed primitives can cause the runtime to advance the current time when awaited.

§Preventing auto-advance

In some testing scenarios, you may want to keep the clock paused without auto-advancing, even while waiting for I/O or other asynchronous operations. This can be achieved by using spawn_blocking to wrap your I/O operations.

When a blocking task is running, the clock’s auto-advance is temporarily inhibited. This allows you to wait for I/O to complete while keeping the paused clock stationary:

use tokio::time::{Duration, Instant};
use tokio::task;

#[tokio::test(start_paused = true)]
async fn test_with_io() {
    let start = Instant::now();

    // The clock will NOT auto-advance while this blocking task runs
    let result = task::spawn_blocking(|| {
        // Perform I/O operations here
        std::thread::sleep(std::time::Duration::from_millis(10));
        42
    }).await.unwrap();

    // Time has not advanced
    assert_eq!(start.elapsed(), Duration::ZERO);
}