【问题标题】:Does Rust have an equivalent of Python's threading.Timer?Rust 是否有 Python 的 threading.Timer 等价物?
【发布时间】:2018-01-15 21:46:14
【问题描述】:

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

from threading import Timer

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

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

【问题讨论】:

    标签: timer rust


    【解决方案1】:

    你可以使用timer crate

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

    【讨论】:

    • 你能用它来更新可变结构中的字段吗?
    • @lsund 如果你的意思是是否可以在闭包中留下一个可变引用,可以从其他地方访问,从板条箱的来源来看,答案似乎是“不”,除非Mutex'd或Arc'd 等参考Cell-and-friends 全局(或unsafe 代码)。
    • (然后还有channelsscoped_tls 之类的,但最后你还是需要用Send-ly 的方式包裹对象)
    【解决方案2】:

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

    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,这确实为每个计时器创建了一个新线程。这可能比重用线程的解决方案更昂贵,但这是一个非常简单的示例。

    【讨论】:

    • 请注意,在每个start 调用中分配一个新线程可能效率低下。
    • @malbarbo 好点!如果您想要一个重复的任务,最好多次一遍又一遍地使用相同的线程,我假设您的答案中的计时器箱确实如此。我只是想匹配 Python 语义。
    猜你喜欢
    • 1970-01-01
    • 2017-04-10
    • 2021-03-29
    • 2012-07-17
    • 2012-06-14
    • 2014-01-09
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多