Expand description
Creates new Interval
that yields with interval of duration
. 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 tokio::time::{self, Duration};
#[tokio::main]
async fn main() {
let mut interval = time::interval(Duration::from_millis(10));
interval.tick().await;
interval.tick().await;
interval.tick().await;
// approximately 20ms have elapsed.
}
A simple example using interval
to execute a task every two seconds.
The difference between interval
and delay_for
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 delay_for
, 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::delay_for(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;
}
}