Skip to main content

advance

Function advance 

Source
pub async fn advance(duration: Duration)
Available on crate features time and test-util only.
Expand description

Advances time.

Increments the saved Instant::now() value by duration. Subsequent calls to Instant::now() will return the result of the increment.

This function will make the current time jump forward by the given duration in one jump. This means that all sleep calls with a deadline before the new time will immediately complete “at the same time”, and the runtime is free to poll them in any order. Additionally, this method will not wait for the sleep calls it advanced past to complete. If you want to do that, you should instead call sleep and rely on the runtime’s auto-advance feature.

Note that calls to sleep are not guaranteed to complete the first time they are polled after a call to advance. For example, this can happen if the runtime has not yet touched the timer driver after the call to advance. However if they don’t, the runtime will poll the task again shortly.

§When to use sleep instead

Important: advance is designed for testing scenarios where you want to instantly jump forward in time. However, it has limitations that make it unsuitable for certain use cases:

  • Forcing timeouts: If you want to reliably trigger a timeout, prefer using sleep with auto-advance rather than advance. The advance function jumps time forward but doesn’t guarantee that all timers will be processed before your code continues.

  • Simulating freezes: If you’re trying to simulate a scenario where the program freezes and then resumes, the batch behavior of advance may not produce the expected results. All timers that expire during the advance complete simultaneously.

For most testing scenarios where you want to wait for a duration to pass and have all timers fire in order, use sleep instead:

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

#[tokio::test(start_paused = true)]
async fn test_timeout_reliable() {
    // Use sleep with auto-advance for reliable timeout testing
    time::sleep(Duration::from_secs(5)).await;
    // All timers that were scheduled to fire within 5 seconds
    // have now been processed in order
}

§Panics

Panics if any of the following conditions are met:

  • The clock is not frozen, which means that you must call pause before calling this method.
  • If called outside of the Tokio runtime.
  • If the input duration is too large (such as Duration::MAX) to be safely added to the current time without causing an overflow.

§Caveats

Using a very large duration is not recommended, as it may cause panicking due to overflow.

§Auto-advance

If the time is paused and there is no work to do, the runtime advances time to the next timer. See pause for more details.