有没有办法在特定时间或间隔安排任务?

Is there a way to schedule a task at a specific time or with an interval?

有没有办法 运行 rust 中的任务,最好是一个线程,在特定时间或间隔一次又一次?

这样我就可以每 5 分钟或每天 12 点 运行 我的功能。

在 Java 中有 TimerTask,所以我正在寻找类似的东西。

您可以使用 Timer::periodic 创建一个定期发送消息的频道,例如

use std::old_io::Timer;

let mut timer = Timer::new().unwrap();
let ticks = timer.periodic(Duration::minutes(5));
for _ in ticks.iter() {
    your_function();
}

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! 计算出接下来应该执行哪个函数。

我相当确定 运行 每天在指定时间正确地使用当前的标准库是不可能的。例如。使用简单的 Timer::periodic(Duration::days(1)) 不会处理系统时钟的变化,例如当用户移动时区或进入 in/out 夏令时。

对于最新的 Rust 每晚版本:

use std::old_io::Timer;
use std::time::Duration;

let mut timer1 = Timer::new().unwrap();
let mut timer2 = Timer::new().unwrap();
let tick1 = timer1.periodic(Duration::seconds(1));
let tick2 = timer2.periodic(Duration::seconds(3));

loop {
    select! {
        _ = tick1.recv() => do_something1(),
        _ = tick2.recv() => do_something2()
    }
}