Rust有相当于Python的线程.Timer?

Tki*_*er2 5 timer rust

我正在寻找一个使用线程的计时器,而不是普通的time.sleep:

from threading import Timer

def x():
    print "hello"
    t = Timer(2.0, x)
    t.start()

t = Timer(2.0, x)
t.start()
Run Code Online (Sandbox Code Playgroud)

mal*_*rbo 7

您可以使用计时器

extern crate timer;
extern crate chrono;

use timer::Timer;
use chrono::Duration;
use std::thread;

fn x() {
    println!("hello");
}

fn main() {
    let timer = Timer::new();
    let guard = timer.schedule_repeating(Duration::seconds(2), x);
    // give some time so we can see hello printed
    // you can execute any code here
    thread::sleep(::std::time::Duration::new(10, 0));
    // stop repeating
    drop(guard);
}
Run Code Online (Sandbox Code Playgroud)


She*_*ter 5

只使用标准库中的工具,自己编写类似版本很容易:

use std::thread;
use std::time::Duration;

struct Timer<F> {
    delay: Duration,
    action: F,
}

impl<F> Timer<F>
where
    F: FnOnce() + Send + Sync + 'static,
{
    fn new(delay: Duration, action: F) -> Self {
        Timer { delay, action }
    }

    fn start(self) {
        thread::spawn(move || {
            thread::sleep(self.delay);
            (self.action)();
        });
    }
}

fn main() {
    fn x() {
        println!("hello");
        let t = Timer::new(Duration::from_secs(2), x);
        t.start();
    }

    let t = Timer::new(Duration::from_secs(2), x);
    t.start();

    // Wait for output
    thread::sleep(Duration::from_secs(10));
}
Run Code Online (Sandbox Code Playgroud)

正如malbarbo指出的,这确实为每个计时器创建了一个新线程.这可能比重用线程的解决方案更昂贵,但这是一个非常简单的例子.