简体   繁体   English

如何使生锈持续时间没有数字计算

[英]how to make the rust duration without number calculate

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 .当我想将间隔设置为 1 小时时,我必须像这样写1000 * 60 * 60的持续时间。 is there any simple way just like Duration::hours(1) ?有没有像Duration::hours(1)这样的简单方法? I have tried the chrono but seems is not compatible with tokio.我试过chrono,但似乎与tokio不兼容。

You can use an extension trait to implement hours() on Duration您可以使用扩展特征在Duration上实现hours()

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")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM