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! 。

相关推荐
理想奋斗中1 分钟前
idea中Lombok失效的解决方案
java·intellij-idea·lombok
保利九里3 分钟前
java中的方法详解
java·开发语言·python
旋风菠萝4 分钟前
项目复习(1)
java·数据库·八股·八股文·复习·项目、
w23617346017 分钟前
Django框架漏洞深度剖析:从漏洞原理到企业级防御实战指南——为什么你的Django项目总被黑客盯上?
数据库·django·sqlite
2302_8097983233 分钟前
【JavaWeb】MySQL
数据库·mysql
.又是新的一天.34 分钟前
使用IDEA创建Maven版本的web项目以及lombok的使用
java·maven·intellij-idea
zimoyin36 分钟前
Java 快速转 C# 教程
java·开发语言·c#
Haooog40 分钟前
Java 面向对象详解和JVM底层内存分析
java·jvm
drowingcoder41 分钟前
MySQL相关
数据库
CopyLower1 小时前
Java在微服务架构中的最佳实践:从设计到部署
java·微服务·架构