首页 文章

Rust是否具有Python的threading.Timer?

提问于
浏览
5

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

from threading import Timer

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

t = Timer(2.0, x)
t.start()

2 回答

  • 5

    您可以使用timer箱子

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

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

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

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

相关问题