Rust 是否有相当于 Python 的线程?定时器?



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

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

您可以使用定时板条箱

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);
}

只使用标准库中的工具即可编写类似的版本:

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));
}

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

最新更新