pub fn interval(period: Duration) -> Interval
Expand description

Creates new Interval that yields with interval of period. The first tick completes immediately. The default MissedTickBehavior is Burst, but this can be configured by calling set_missed_tick_behavior.

An interval will tick indefinitely. At any time, the Interval value can be dropped. This cancels the interval.

This function is equivalent to interval_at(Instant::now(), period).

Panics

This function panics if period is zero.

Examples

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

#[tokio::main]
async fn main() {
    let mut interval = time::interval(Duration::from_millis(10));

    interval.tick().await; // ticks immediately
    interval.tick().await; // ticks after 10ms
    interval.tick().await; // ticks after 10ms

    // approximately 20ms have elapsed.
}

A simple example using interval to execute a task every two seconds.

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 sleep, the task would only be executed once every three seconds, and not every two seconds.

use tokio::time;

async fn task_that_takes_a_second() {
    println!("hello");
    time::sleep(time::Duration::from_secs(1)).await
}

#[tokio::main]
async fn main() {
    let mut interval = time::interval(time::Duration::from_secs(2));
    for _i in 0..5 {
        interval.tick().await;
        task_that_takes_a_second().await;
    }
}