【发布时间】: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()
【问题讨论】:
我正在寻找一个使用线程的计时器,而不是普通的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 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);
}
【讨论】:
Mutex'd或Arc'd 等参考Cell-and-friends 全局(或unsafe 代码)。
Send-ly 的方式包裹对象)
自己编写一个类似的版本很容易,只使用标准库中的工具:
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 调用中分配一个新线程可能效率低下。