Reputation: 38681
I using this code to do an interval in rust:
use std::time::Duration;
use tokio::time;
#[tokio::main]
async fn main() {
let mut interval = time::interval(Duration::from_millis(10000));
loop {
interval.tick().await;
println!("{}","trigger")
}
}
When I want to set the interval to 1 hour, I have to write the Duration like this 1000 * 60 * 60
. is there any simple way just like Duration::hours(1)
? I have tried chrono
but seems it is not compatible with Tokio.
Upvotes: 0
Views: 1199
Reputation: 119
You can use an extension trait to implement hours()
on Duration
use std::time::Duration;
use tokio::time;
trait DurationExt {
fn from_hours(hours: u64) -> Duration;
}
impl DurationExt for Duration {
fn from_hours(hours: u64) -> Duration {
Duration::from_secs(hours * 60 * 60)
}
}
#[tokio::main]
async fn main() {
let mut interval = time::interval(Duration::from_hours(1));
loop {
interval.tick().await;
println!("{}","trigger")
}
}
Upvotes: 1