有没有办法在新线程上启动tokio :: Delay以允许主循环继续? [英] Is there a way to launch a tokio::Delay on a new thread to allow the main loop to continue?

查看:231
本文介绍了有没有办法在新线程上启动tokio :: Delay以允许主循环继续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有取消计时器,我试图在延迟结束时运行功能.用例是按住并双击以供用户输入.

I am trying to run a function at the end of a delay if the timer is not canceled. The use case is a press and hold / double tap for user input.

我遇到的主要问题是tokio::run(task);阻止了主循环的执行,从而使我无法评估用户控件的状态.

The main issue that I am having is that the tokio::run(task); stops the main loop from executing thus prevents me from evaluating the state of the users control.

fn start_timer(&self) {
    let function_name = self.combo.function_name.clone();
    let when = Instant::now() + Duration::from_millis(self.combo.timer_value as u64);
    let task = Delay::new(when)
        .and_then(move |_| {
            call_function(&function_name, InteropParams::Button);
            Ok(())
        })
        .map_err(|e| panic!("delay errored; err={:?}", e));

    tokio::run(task);
}

推荐答案

是的,您可以启动一个新的OS级线程并在其中运行Tokio事件循环:

Yes, you can start a new OS level thread and run a Tokio event loop there:

use futures::future::Future; // 0.1.25
use std::{
    thread,
    time::{Duration, Instant},
};
use tokio::timer::Delay; // 0.1.14 

fn main() {
    let t = thread::spawn(|| {
        let when = Instant::now() + Duration::from_millis(100);
        let task = Delay::new(when)
            .and_then(move |_| {
                println!("Delay expired");
                Ok(())
            })
            .map_err(|e| panic!("delay errored: {}", e));

        tokio::run(task);
    });

    t.join().unwrap();
}

您还可以通过 tokio::spawn :

You can also use Tokio's tasks via tokio::spawn:

use futures::future::{self, Future}; // 0.1.25
use std::time::{Duration, Instant};
use tokio::timer::Delay; // 0.1.14

fn main() {
    tokio::run(future::lazy(|| {
        tokio::spawn({
            let when = Instant::now() + Duration::from_millis(100);
            Delay::new(when)
                .and_then(move |_| {
                    println!("Delay 100 expired");
                    Ok(())
                })
                .map_err(|e| panic!("delay errored: {}", e))
        });

        tokio::spawn({
            let when = Instant::now() + Duration::from_millis(200);
            Delay::new(when)
                .and_then(move |_| {
                    println!("Delay 200 expired");
                    Ok(())
                })
                .map_err(|e| panic!("delay errored: {}", e))
        });

        future::ok::<_, ()>(())
    }))
}

这篇关于有没有办法在新线程上启动tokio :: Delay以允许主循环继续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆