rust 同时处理多个异步任务

rust 复制代码
use tokio::{sync::oneshot, time::{sleep, Duration}};

async fn check_for_one() {
    // This loop will continuously print "write" every second until interrupted
    loop {
        println!("write");
        sleep(Duration::from_secs(1)).await; // Non-blocking sleep in async context
    }
}

#[tokio::main]
async fn main() {
    // Create a oneshot channel
    let (tx1, rx1) = oneshot::channel::<&str>();

    // Spawn a task that sends a message after 2 seconds
    tokio::spawn(async move {
        sleep(Duration::from_secs(2)).await;    
        let _ = tx1.send("one");
    });

    // Use tokio::select! to wait for either the print task or the message on rx1
    tokio::select! {
        _ = check_for_one() => {
            // This branch will continuously print "write" every second
            println!("check_for_one completed");
        }
        val = rx1 => {
            // This branch will be executed once the message is received from rx1
            match val {
                Ok(val) => println!("rx1 completed first with {:?}", val),
                Err(e) => println!("Failed to receive from rx1: {:?}", e),
            }
        }
    }

    println!("main thread exiting"); 
}

只要有一个异步任务完成,就会退出select! 。

相关推荐
SelectDB1 小时前
开源日志平台怎么选?ELK、Loki、ClickHouse、Apache Doris 四大方案对比与选型指南
数据库
SelectDB1 小时前
ELK 磁盘空间不足怎么办?Elasticsearch 存储膨胀原因、排查步骤与 3 种降本方案
数据库
满小满2 小时前
为什么我先 ANALYZE,而不是先加索引
数据库·dba
geovindu2 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
SelectDB2 小时前
日志分析用什么数据库好?Elasticsearch、ClickHouse、Doris 选型对比与 3 个企业案例
数据库
喵个咪2 小时前
RushWind Admin — 模块化单体:一个进程与通往微服务的五级阶梯
后端·架构·rust
喵个咪3 小时前
RushWind CMS — 最小微服务实例:微服务架构的最小完备集
后端·架构·rust
inferno4 小时前
十三、存储过程(PROCEDURE)
数据库·sql·mysql
数据库急诊室_阿哲4 小时前
一周慢查询日志审计:1200 条里有多少真问题
运维·数据库·dba
zhangjw345 小时前
2-4 集合运算 union /union all /intersect/except
数据库·postgresql