有没有办法在特定时间或间隔安排任务?
有没有办法在 Rust 中运行一个任务,最好是一个线程,在特定时间或间隔一次又一次地运行?
Is there a way to run a task in rust, a thread at best, at a specific time or in an interval again and again?
这样我就可以每 5 分钟或每天 12 点运行一次我的函数.
So that I can run my function every 5 minutes or every day at 12 o'clock.
在 Java 中有 TimerTask,所以我正在寻找类似的东西.
In Java there is the TimerTask, so I'm searching for something like that.
您可以使用 Timer::periodic
创建一个以固定间隔发送消息的通道,例如
You can use Timer::periodic
to create a channel that gets sent a message at regular intervals, e.g.
use std::old_io::Timer;
let mut timer = Timer::new().unwrap();
let ticks = timer.periodic(Duration::minutes(5));
for _ in ticks.iter() {
your_function();
}
接收器::iter
阻塞,等待下一条消息,这些消息相隔 5 分钟,因此 for
循环的主体以这些固定间隔运行.注意.这将为该单个函数使用整个线程,但我相信可以通过创建多个计时器通道并使用 select!
以确定接下来应该执行哪个函数.
Receiver::iter
blocks, waiting for the next message, and those messages are 5 minutes apart, so the body of the for
loop is run at those regular intervals. NB. this will use a whole thread for that single function, but I believe one can generalise to any fixed number of functions with different intervals by creating multiple timer channels and using select!
to work out which function should execute next.
我相当确定,在当前的标准库中,每天在指定时间正确运行是不可能的.例如.使用简单的 Timer::periodic(Duration::days(1))
不会处理系统时钟的变化,例如当用户移动时区或进入/退出夏令时.
I'm fairly sure that running every day at a specified time, correctly, isn't possible with the current standard library. E.g. using a simple Timer::periodic(Duration::days(1))
won't handle the system clock changing, e.g. when the user moves timezones, or goes in/out of daylight savings.