一东京任务可以正常终止整个运行?

问题描述 投票:2回答:1

我开始了这样的代码运行东京:

tokio::run(my_future);

我的未来继续展开一串任务响应各种条件。

其中的一个任务是负责确定何时程序应该关闭。不过,我不知道如何有一个任务正常终止的程序。理想情况下,我想找到这个任务的方式来引起run函数调用来终止。

下面是一种方案,我想写的一个例子:

extern crate tokio;

use tokio::prelude::*;

use std::time::Duration;
use std::time::Instant;

use tokio::timer::{Delay, Interval};

fn main() {
    let kill_future = Delay::new(Instant::now() + Duration::from_secs(3));

    let time_print_future = Interval::new_interval(Duration::from_secs(1));

    let mut runtime = tokio::runtime::Runtime::new().expect("failed to start new Runtime");
    runtime.spawn(time_print_future.for_each(|t| Ok(println!("{:?}", t))).map_err(|_| ()));
    runtime.spawn(
        kill_future
            .map_err(|_| {
                eprintln!("Timer error");
            })
            .map(move |()| {
                // TODO
                unimplemented!("Shutdown the runtime!");
            }),
    );
    // TODO
    unimplemented!("Block until the runtime is shutdown");
    println!("Done");
}

shutdown_now很有前途,但在进一步的调查,它可能行不通。特别是,它需要运行的所有权,而东京则可能不会允许两个主线程(在其中创建运行时)和一些随机任务自己的运行时间。

rust rust-tokio
1个回答
2
投票

您可以使用oneshot channel从运行时间内传达给外界。当延迟期满时,我们通过通道发送的单个消息。

在运行时之外,一旦我们收到消息,我们开始运行时和wait其完成的关闭。

use std::time::{Duration, Instant};
use tokio::{
    prelude::*,
    runtime::Runtime,
    sync::oneshot,
    timer::{Delay, Interval},
}; // 0.1.15

fn main() {
    let mut runtime = Runtime::new().expect("failed to start new Runtime");

    let (tx, rx) = oneshot::channel();

    runtime.spawn({
        let every_second = Interval::new_interval(Duration::from_secs(1));
        every_second
            .for_each(|t| Ok(println!("{:?}", t)))
            .map_err(drop)
    });

    runtime.spawn({
        let in_three_seconds = Delay::new(Instant::now() + Duration::from_secs(3));
        in_three_seconds
            .map_err(|_| eprintln!("Timer error"))
            .and_then(move |_| tx.send(()))
    });

    rx.wait().expect("unable to wait for receiver");
    runtime
        .shutdown_now()
        .wait()
        .expect("unable to wait for shutdown");

    println!("Done");
}

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.