当前位置: 首页 > news >正文

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:50Current 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:53Current 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:56Current 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:59Current 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:29Current 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:34Current 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:39Current 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:44Current 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 3slet now: DateTime<Local> = Local::now();println!("Current task time now is: {}", now.format("%Y-%m-%d %H:%M:%S"));interval.tick().await; // ticks after 3slet now: DateTime<Local> = Local::now();println!("Current task time now is: {}", now.format("%Y-%m-%d %H:%M:%S"));interval.tick().await; // ticks after 3slet 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 频率计时器在某个周期中错过某个间隔时如何处理。具体来说,它有以下三个变体:

  • 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

示例 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.…...

Java 中 List 集合排序方法

方式一&#xff1a; 调用List接口自己的sort方法排序 public static void main(String[] args) {List<Integer> numListnew ArrayList<>();numList.add(999);numList.add(123);numList.add(456);numList.add(66);numList.add(9);Collections.sort(numList); //使…...

prometheus监控k8s服务并告警到钉钉

一、监控k8s集群 要监控k8s集群需要使用到以下服务用于收集监控的资源信息&#xff0c;node_exporter用于监控k8s集群节点的资源信息&#xff0c;kube-state-metrics用于监控k8s集群的deployment、statefulset、daemonset、pod等的状态&#xff0c;cadvisor用于监控k8s集群的p…...

Go和Java实现解释器模式

Go和Java实现解释器模式 下面通过一个四则运算来说明解释器模式的使用。 1、解释器模式 解释器模式提供了评估语言的语法或表达式的方式&#xff0c;它属于行为型模式。这种模式实现了一个表达式接口&#xff0c;该接口 解释一个特定的上下文。这种模式被用在 SQL 解析、符…...

域名配置HTTPS

一、注册域名 这个可以在各大平台注册&#xff0c;具体看一下就会注册了&#xff0c;自己挑选一个自己喜欢的域名。 步骤一般也就是先实名&#xff0c;实名成功了才能注册域名。 二、办理SSL证书 这里使用的是阿里云的SSL免费证书 1、申请证书 二、填写申请 三、域名绑定生…...

机械设计cad,ug编程设计,ug模具设计,SolidWorks模具设计

模具设计培训课程&#xff1a; 【第一阶段&#xff1a;CAD识图制图】 [AutoCAD机械制图]&#xff1a;全面讲解AUTOCAD应用知识&#xff0c;常用命令讲解与运用&#xff0c;二维平面图绘制&#xff0c;三维成型零件的绘制与设计&#xff0c;制作工程图 【第二阶段&#xff1a;U…...

嵌入式开发的学习与未来展望:借助STM32 HAL库开创创新之路

引言&#xff1a; 嵌入式开发作为计算机科学领域的重要分支&#xff0c;为我们的日常生活和产业发展提供了无限的可能。STMicroelectronics的STM32系列芯片以其出色的性能和广泛的应用领域而备受关注。而STM32 HAL库作为嵌入式开发的高级库&#xff0c;为学习者提供了更高效、更…...

WPS-0DAY-20230809的分析和利用复现

WPS-0DAY-20230809的分析和初步复现 一、漏洞学习1、本地复现环境过程 2、代码解析1.htmlexp.py 3、通过修改shellcode拿shell曲折的学习msf生成sc 二、疑点1、问题2、我的测试测试方法测试结果 一、漏洞学习 强调&#xff1a;以下内容仅供学习和测试&#xff0c;一切行为均在…...

MongoDB(三十九)

目录 一、概述 &#xff08;一&#xff09;相关概念 &#xff08;二&#xff09;特性 二、应用场景 三、安装 &#xff08;一&#xff09;编译安装 &#xff08;二&#xff09;yum安装 1、首先制作repo源 2、软件包名&#xff1a;mongodb-org 3、启动服务&#xff1a…...

InnoDB引擎

1 逻辑存储结构 InnoDB的逻辑存储结构如下图所示: 1). 表空间 表空间是InnoDB存储引擎逻辑结构的最高层&#xff0c; 如果用户启用了参数 innodb_file_per_table(在8.0版本中默认开启) &#xff0c;则每张表都会有一个表空间&#xff08;xxx.ibd&#xff09;&#xff0c;一个…...

CSS3中的var()函数

目录 定义&#xff1a; 语法&#xff1a; 用法&#xff1a; 定义&#xff1a; var()函数是一个 CSS 函数用于插入自定义属性&#xff08;有时也被称为“CSS 变量”&#xff09;的值 语法&#xff1a; var(custom-property-name, value) 函数的第一个参数是要替换的自定义属性…...

opencv图片换背景色

#include <iostream> #include<opencv2/opencv.hpp> //引入头文件using namespace cv; //命名空间 using namespace std;//opencv这个机器视觉库&#xff0c;它提供了很多功能&#xff0c;都是以函数的形式提供给我们 //我们只需要会调用函数即可in…...

JAVA语言:什么是懒加载机制?

JVM没有规定什么时候加载,一般是什么时候使用这个class才会什么时候加载,但是JVM规定了什么时候必须初始化(初始化是第三步、装载、连接、初始化),只要加载之后,那么肯定是要进行初始化的,所以我们就可以通过查看这个类有没有进行初始化,从而判断这个类有没有被加载。 …...

jupyter默认工作目录的更改

1、生成配置文件&#xff1a;打开Anaconda Prompt&#xff0c;输入如下命令 jupyter notebook --generate-config询问[y/N]时输入y 2、配置文件修改&#xff1a;根据打印路径打开配置文件jupyter_notebook_config.py&#xff0c;全文搜索找到notebook_dir所在位置。在单引号中…...

Flutter系列文章-Flutter UI进阶

在本篇文章中&#xff0c;我们将深入学习 Flutter UI 的进阶技巧&#xff0c;涵盖了布局原理、动画实现、自定义绘图和效果、以及 Material 和 Cupertino 组件库的使用。通过实例演示&#xff0c;你将更加了解如何创建复杂、令人印象深刻的用户界面。 第一部分&#xff1a;深入…...

Elasticsearch在部署时,对Linux的设置有哪些优化方法?

部署Elasticsearch时&#xff0c;可以通过优化Linux系统的设置来提升性能和稳定性。以下是一些常见的优化方法&#xff1a; 1.文件描述符限制 Elasticsearch需要大量的文件描述符来处理数据和连接&#xff0c;所以确保调整系统的文件描述符限制。可以通过修改 /etc/security/…...

【网络基础】应用层协议

【网络基础】应用层协议 文章目录 【网络基础】应用层协议1、协议作用1.1 应用层需求1.2 协议分类 2、HTTP & HTTPS2.1 HTTP/HTTPS 简介2.2 HTTP工作原理2.3 HTTPS工作原理2.4 区别 3、URL3.1 编码解码3.2 URI & URL 4、HTTP 消息结构4.1 HTTP请求方法4.2 HTTP请求头信…...

面试八股文Mysql:(1)事务实现的原理

1. 什么是事务 事务就是一组数据库操作&#xff0c;这些操作是一个atomic&#xff08;原子性的操作&#xff09; &#xff0c;不可分割&#xff0c;要么都执行&#xff0c;要么回滚&#xff08;rollback&#xff09;都不执行。这样就避免了某个操作成功某个操作失败&#xff0…...

Linux学习之sed多行模式

N将下一行加入到模式空间 D删除模式空间中的第一个字符到第一个换行符 P打印模式空间中的第一个字符到第一个换行符 doubleSpace.txt里边的内容如下&#xff1a; goo d man使用下边的命令可以实现把上边对应的内容放到doubleSpace.txt。 echo goo >> doubleSpace.txt e…...

【刷题笔记8.15】【链表相关】LeetCode:合并两个有序链表、反转链表

LeetCode&#xff1a;【链表相关】合并两个有序链表 题目1&#xff1a;合并两个有序链表 题目描述 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 输入&#xff1a;l1 [1,2,4], l2 [1,3,4] 输出&#xff1a;[1,1,2,3…...

douyin-downloader完全指南:音频高效提取的创新方法

douyin-downloader完全指南&#xff1a;音频高效提取的创新方法 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fallback support…...

珠海内有哪些做专精特新,创新型中小企业。权代理事务通过率高

在珠海&#xff0c;众多专精特新、创新型中小企业在发展过程中&#xff0c;知识产权代理事务变得尤为重要&#xff0c;而珠海飞拓知识产权代理事务凭借其独特优势&#xff0c;成为了高通过率的代表。企业痛点催生专业服务在专精特新、创新型中小企业培育与申报过程中&#xff0…...

记录模式 vs Lombok vs Record类,全维度性能与可维护性对比测试(含JMH压测数据)

第一章&#xff1a;Java记录模式的核心概念与演进背景Java记录模式&#xff08;Record Patterns&#xff09;是JDK 21中正式引入的预览特性&#xff08;JEP 440&#xff09;&#xff0c;并在JDK 22中进一步增强&#xff08;JEP 441&#xff09;&#xff0c;旨在为结构化数据解构…...

JAVA重点基础、进阶知识及易错点总结(17)线程安全 synchronized 同步锁

&#x1f680; Java 巩固进阶 第17天 主题&#xff1a;线程安全 & synchronized 同步锁 —— 并发编程的第一道防线&#x1f4c5; 进度概览&#xff1a;今天攻克 多线程最核心难题&#xff1a;线程安全。这是面试必考、生产环境必用的知识点&#xff0c;直接决定你的代码能…...

RAGFlow知识库配置与RAG流程优化实战

1. RAGFlow知识库配置详解 第一次接触RAGFlow知识库时&#xff0c;我被它强大的文档处理能力惊艳到了。记得当时处理一批科研论文PDF&#xff0c;传统方法提取的内容总是支离破碎&#xff0c;而RAGFlow的DeepDoc解析器完美保留了文档的图表和章节结构。下面我就把踩坑后总结的配…...

基于MATLAB的用于分析弧齿锥齿轮啮合轨迹的程序已调通,可直接运行并输出齿轮啮合轨迹及传递误差

158.基于matlab的用于分析弧齿锥齿轮啮合轨迹的输出齿轮啮合轨迹及传递误差程序已调通&#xff0c;可直接运行 1. 程序概述 本程序包实现了一套完整的弧齿锥齿轮齿面接触分析&#xff08;TCA&#xff09; 系统&#xff0c;主要用于分析大轮凸面与小轮凹面的啮合特性。程序由刘…...

I.MX6U-MINI开发板系统固化全流程:从uboot编译到rootfs烧录(附网络配置技巧)

I.MX6U-MINI开发板系统固化实战指南&#xff1a;从零构建到网络调优 第一次拿到I.MX6U-MINI开发板时&#xff0c;面对系统固化的多个环节总有种无从下手的感觉。作为嵌入式Linux开发的入门门槛&#xff0c;系统固化不仅关系到后续应用开发的基础环境&#xff0c;更是理解嵌入式…...

前端 HTML 转 PDF

spdf 两个库转换成 PDF 文件并下载到本地。 简单说&#xff1a;它能让用户 “一键下载” 网页上的某个区域为 PDF&#xff08;比如报表、数据统计页、合同预览页等&#xff09;&#xff0c;还预留了 “水印功能” 的注释代码&#xff08;可按需启用&#xff09;。 核心依赖说…...

5分钟精通B站音频提取:从新手到高手的开源工具实战指南

5分钟精通B站音频提取&#xff1a;从新手到高手的开源工具实战指南 【免费下载链接】BilibiliDown (GUI-多平台支持) B站 哔哩哔哩 视频下载器。支持稍后再看、收藏夹、UP主视频批量下载|Bilibili Video Downloader &#x1f633; 项目地址: https://gitcode.com/gh_mirrors/…...

如何三步搞定iOS微信聊天记录完整导出:隐私保护与数据备份终极指南

如何三步搞定iOS微信聊天记录完整导出&#xff1a;隐私保护与数据备份终极指南 【免费下载链接】WeChatExporter 一个可以快速导出、查看你的微信聊天记录的工具 项目地址: https://gitcode.com/gh_mirrors/wec/WeChatExporter 还在为无法永久保存重要微信对话而烦恼吗&…...