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));
}
2 回答
您可以使用timer箱子
只使用标准库中的工具,自己编写类似版本很容易:
作为pointed out by malbarbo,这确实为每个计时器创建了一个新线程 . 这可能比重用线程的解决方案更昂贵,但这是一个非常简单的例子 .