compio_runtime::time

Function interval

Source
pub fn interval(period: Duration) -> Interval
Available on crate feature time only.
Expand description

Creates new Interval that yields with interval of period. The first tick completes immediately.

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 std::time::Duration;

use compio_runtime::time::interval;

let mut interval = 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 std::time::Duration;

use compio_runtime::time::{interval, sleep};

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

let mut interval = interval(Duration::from_secs(2));
for _i in 0..5 {
    interval.tick().await;
    task_that_takes_a_second().await;
}