rust学习-tokio::time

这篇具有很好参考价值的文章主要介绍了rust学习-tokio::time。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

示例

use std::time::Duration;
use tokio::{task, time::interval};

#[tokio::main]
async fn main() {
    let mut interval = interval(Duration::from_secs(1));
    let handle = task::spawn(async move {
        loop {
            interval.tick().await;
            println!("tick");
        }
    });

    handle.await.unwrap();
}

interval和sleep的区别

tick周期大于异步任务周期

use tokio::time;
use chrono::{DateTime, Local};

async fn task_that_takes_a_second() {
    let now: DateTime<Local> = Local::now();
    println!("Current task time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    time::sleep(time::Duration::from_secs(2)).await;
    let now: DateTime<Local> = Local::now();
    println!("Current task time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
}

#[tokio::main]
async fn main() {
    let mut interval = time::interval(time::Duration::from_secs(3));
    for _i in 0..5 {
        let now: DateTime<Local> = Local::now();
        println!("Current main time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
        interval.tick().await;
        let now: DateTime<Local> = Local::now();
        println!("Current main time mid is: {}", now.format("%Y-%m-%d %H:%M:%S"));
        task_that_takes_a_second().await;
        let now: DateTime<Local> = Local::now();
        println!("Current main time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    }
}
Current main time before is: 2023-08-11 13:46:48
Current main time mid is: 2023-08-11 13:46:48 // 第一次,立即触发
Current task time before is: 2023-08-11 13:46:48
Current task time after is: 2023-08-11 13:46:50
Current main time after is: 2023-08-11 13:46:50

Current main time before is: 2023-08-11 13:46:50
Current main time mid is: 2023-08-11 13:46:51 // 距离上一次3秒
Current task time before is: 2023-08-11 13:46:51
Current task time after is: 2023-08-11 13:46:53
Current main time after is: 2023-08-11 13:46:53

Current main time before is: 2023-08-11 13:46:53
Current main time mid is: 2023-08-11 13:46:54 // 距离上一次3秒
Current task time before is: 2023-08-11 13:46:54
Current task time after is: 2023-08-11 13:46:56
Current main time after is: 2023-08-11 13:46:56

Current main time before is: 2023-08-11 13:46:56
Current main time mid is: 2023-08-11 13:46:57  // 距离上一次3秒
Current task time before is: 2023-08-11 13:46:57
Current task time after is: 2023-08-11 13:46:59
Current main time after is: 2023-08-11 13:46:59

Current main time before is: 2023-08-11 13:46:59
Current main time mid is: 2023-08-11 13:47:00 // 距离上一次3秒
Current task time before is: 2023-08-11 13:47:00
Current task time after is: 2023-08-11 13:47:02
Current main time after is: 2023-08-11 13:47:02

tick周期小于异步任务周期

use tokio::time;
use chrono::{DateTime, Local};

async fn task_that_takes_a_second() {
    let now: DateTime<Local> = Local::now();
    println!("Current task time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    time::sleep(time::Duration::from_secs(5)).await;
    let now: DateTime<Local> = Local::now();
    println!("Current task time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
}

#[tokio::main]
async fn main() {
    let mut interval = time::interval(time::Duration::from_secs(3));
    for _i in 0..5 {
        let now: DateTime<Local> = Local::now();
        println!("Current main time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
        interval.tick().await;
        let now: DateTime<Local> = Local::now();
        println!("Current main time mid is: {}", now.format("%Y-%m-%d %H:%M:%S"));
        task_that_takes_a_second().await;
        let now: DateTime<Local> = Local::now();
        println!("Current main time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    }
}
Current main time before is: 2023-08-11 13:51:24
Current main time mid is: 2023-08-11 13:51:24
Current task time before is: 2023-08-11 13:51:24
Current task time after is: 2023-08-11 13:51:29
Current main time after is: 2023-08-11 13:51:29

Current main time before is: 2023-08-11 13:51:29
Current main time mid is: 2023-08-11 13:51:29 // 举例上一次超过3秒
Current task time before is: 2023-08-11 13:51:29
Current task time after is: 2023-08-11 13:51:34
Current main time after is: 2023-08-11 13:51:34

Current main time before is: 2023-08-11 13:51:34
Current main time mid is: 2023-08-11 13:51:34  // 举例上一次超过3秒
Current task time before is: 2023-08-11 13:51:34
Current task time after is: 2023-08-11 13:51:39
Current main time after is: 2023-08-11 13:51:39

Current main time before is: 2023-08-11 13:51:39
Current main time mid is: 2023-08-11 13:51:39  // 举例上一次超过3秒
Current task time before is: 2023-08-11 13:51:39
Current task time after is: 2023-08-11 13:51:44
Current main time after is: 2023-08-11 13:51:44

Current main time before is: 2023-08-11 13:51:44
Current main time mid is: 2023-08-11 13:51:44  // 举例上一次超过3秒
Current task time before is: 2023-08-11 13:51:44
Current task time after is: 2023-08-11 13:51:49
Current main time after is: 2023-08-11 13:51:49

timeout

use tokio::time::{timeout, Duration};
use tokio::time;
use chrono::{DateTime, Local};

async fn long_future() {
    let now: DateTime<Local> = Local::now();
    println!("Current task time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    time::sleep(time::Duration::from_secs(5)).await;
    let now: DateTime<Local> = Local::now();
    println!("Current task time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
}

#[tokio::main]
async fn main() {
    for _i in 0..5 {
        let now: DateTime<Local> = Local::now();
        println!("Current main time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    
        let res = timeout(Duration::from_secs(1), long_future()).await;
    
        let now: DateTime<Local> = Local::now();
        println!("Current main time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
        
        if res.is_err() {
                println!("operation timed out");
        }
    }
}

interval_at

pub fn interval_at(start: Instant, period: Duration) -> Interval
use tokio::time::{interval_at, Duration, Instant};
use chrono::{DateTime, Local};

#[tokio::main]
async fn main() {
    let start = Instant::now() + Duration::from_secs(5);
    let mut interval = interval_at(start, Duration::from_secs(3)); // 不会立即开始

    let now: DateTime<Local> = Local::now();
    println!("Current task time now is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    interval.tick().await; // ticks after 3s
    let now: DateTime<Local> = Local::now();
    println!("Current task time now is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    interval.tick().await; // ticks after 3s
    let now: DateTime<Local> = Local::now();
    println!("Current task time now is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    interval.tick().await; // ticks after 3s
    let now: DateTime<Local> = Local::now();
    println!("Current task time now is: {}", now.format("%Y-%m-%d %H:%M:%S"));
}
Current task time now is: 2023-08-11 19:34:30
Current task time now is: 2023-08-11 19:34:35
Current task time now is: 2023-08-11 19:34:38
Current task time now is: 2023-08-11 19:34:41

MissedTickBehavior

use tokio::time;
use chrono::{DateTime, Local};
use tokio::time::MissedTickBehavior;

async fn task_that_takes_a_second() {
    let now: DateTime<Local> = Local::now();
    println!("Current task time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    time::sleep(time::Duration::from_secs(5)).await;
    let now: DateTime<Local> = Local::now();
    println!("Current task time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
}

#[tokio::main]
async fn main() {
    let mut interval = time::interval(time::Duration::from_secs(3));
    interval.set_missed_tick_behavior(MissedTickBehavior::Delay);

        for _i in 0..5 {
            let now: DateTime<Local> = Local::now();
            println!("Current main time before is: {}", now.format("%Y-%m-%d %H:%M:%S"));
            interval.tick().await;
            let now: DateTime<Local> = Local::now();
            println!("Current main time mid is: {}", now.format("%Y-%m-%d %H:%M:%S"));
            task_that_takes_a_second().await;
            let now: DateTime<Local> = Local::now();
            println!("Current main time after is: {}", now.format("%Y-%m-%d %H:%M:%S"));
    }
}

在 Rust 的 tokio 库中,MissedTickBehavior 是一个枚举类型,表示当 Interval 频率计时器在某个周期中错过某个间隔时如何处理。具体来说,它有以下三个变体:文章来源地址https://www.toymoban.com/news/detail-647947.html

  • Burst:表示如果错过计时间隔,则会立即执行多个周期,直到被重新赶上。
  • Delay:表示如果错过计时间隔,则在下一个可用的计时间隔时执行周期。
  • Skip:表示如果错过计时间隔,则跳过它并继续执行下一个计时间隔的周期。
    一般情况下, Burst 和 Delay 会导致执行速率加速,Skip 会导致执行速率降低但保证数据与频率同步。
#[tokio::main]
async fn main() {
    let mut interval_burst = time::interval(Duration::from_millis(5));
    interval_burst.set_missed_tick_behavior(time::MissedTickBehavior::Burst);

    let mut interval_delay = time::interval(Duration::from_millis(5));
    interval_delay.set_missed_tick_behavior(time::MissedTickBehavior::Delay);

    let mut count_burst = 0;
    let mut count_delay = 0;

    // 运行到20000次以上才会看出差异
    loop {
        select! {
            _ = interval_burst.tick() => {
                count_burst += 1;
                println!("Burst: tick #{}", count_burst);
            }
            _ = interval_delay.tick() => {
                count_delay += 1;
                println!("Delay: tick #{}", count_delay);
            }
        }
    }
}

到了这里,关于rust学习-tokio::time的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 用Rust设计一个并发的Web服务:常用Rust库如Tokio、Hyper等,基于TCP/IP协议栈,实现了一个简单的并发Web服务器,并结合具体的代码讲解如何编写并发Web服务器的程序

    作者:禅与计算机程序设计艺术 1994年,互联网泡沫破裂,一批优秀的程序员、工程师纷纷加入到web开发领域。而其中的Rust语言却备受瞩目,它是一种现代系统编程语言,专注于安全和并发。因此,Rust在当下成为最流行的编程语言之一,很多框架也开始使用Rust重构,这使得

    2024年02月06日
    浏览(52)
  • 【Rust学习】安装Rust环境

    本笔记为了记录学习Rust过程,内容如有错误请大佬指教 使用IDE:vs code 参考教程:菜鸟教程链接: 菜鸟教程链接: 因为我已经安装过VSCode了,所以VSCode的安装方法在此处就不多介绍了,接下来就是安装Rust的编译工具。 Rust 编译工具 可以点击跳转下载Rust 编译工具 新建文件夹,

    2024年01月17日
    浏览(55)
  • Training-Time-Friendly Network for Real-Time Object Detection 论文学习

    目前的目标检测器很少能做到快速训练、快速推理,并同时保持准确率。直觉上,推理越快的检测器应该训练也很快,但大多数的实时检测器反而需要更长的训练时间。准确率高的检测器大致可分为两类:推理时间久的的训练时间久的。 推理时间久的检测器一般依赖于复杂的

    2024年02月15日
    浏览(35)
  • 计算机网路学习-time_wait过多

    netstat -an|awk ‘/tcp/ {print $6}’|sort|uniq -c netstat -an 列出系统中所有处于活动状态的网络连接信息,包括 IP 地址、端口号、协议等。 其中,第六列是tcp的状态。 awk ‘/tcp/ {print $6}’ 按行进行匹配,筛选出包含 tcp 的行,只输出符合条件的结果 过滤 TCP 类型的连接,然后输出连接

    2024年02月09日
    浏览(34)
  • 【Rust】Rust学习 第十七章Rust 的面向对象特性

    面向对象编程(Object-Oriented Programming,OOP)是一种模式化编程方式。对象(Object)来源于 20 世纪 60 年代的 Simula 编程语言。这些对象影响了 Alan Kay 的编程架构中对象之间的消息传递。他在 1967 年创造了  面向对象编程  这个术语来描述这种架构。关于 OOP 是什么有很多相互矛

    2024年02月11日
    浏览(37)
  • 【Rust】Rust学习 第九章错误处理

    Rust 将错误组合成两个主要类别: 可恢复错误 ( recoverable )和  不可恢复错误 ( unrecoverable )。可恢复错误通常代表向用户报告错误和重试操作是合理的情况,比如未找到文件。不可恢复错误通常是 bug 的同义词,比如尝试访问超过数组结尾的位置。 大部分语言并不区分这

    2024年02月13日
    浏览(34)
  • 【Rust】Rust学习 第八章常见集合

    Rust 标准库中包含一系列被称为  集合 ( collections )的非常有用的数据结构。大部分其他数据类型都代表一个特定的值,不过集合可以包含多个值。不同于内建的数组和元组类型,这些集合指向的数据是储存在堆上的,这意味着数据的数量不必在编译时就已知,并且还可以随

    2024年02月13日
    浏览(33)
  • 【Rust】Rust学习 第十六章无畏并发

    安全且高效的处理并发编程是 Rust 的另一个主要目标。 并发编程( Concurrent programming ),代表程序的不同部分相互独立的执行,而 并行编程( parallel programming )代表程序不同部分于同时执行 ,这两个概念随着计算机越来越多的利用多处理器的优势时显得愈发重要。由于历

    2024年02月12日
    浏览(34)
  • 【Rust】Rust学习 第十五章智能指针

    指针  ( pointer )是一个包含内存地址的变量的通用概念。这个地址引用,或 “指向”(points at)一些其他数据。Rust 中最常见的指针是第四章介绍的  引用 ( reference )。引用以   符号为标志并借用了他们所指向的值。除了引用数据没有任何其他特殊功能。它们也没有任

    2024年02月12日
    浏览(28)
  • 【Rust】Rust学习 第十九章高级特征

    现在我们已经学习了 Rust 编程语言中最常用的部分。在第二十章开始另一个新项目之前,让我们聊聊一些总有一天你会遇上的部分内容。你可以将本章作为不经意间遇到未知的内容时的参考。本章将要学习的功能在一些非常特定的场景下很有用处。虽然很少会碰到它们,我们

    2024年02月11日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包