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

给你一囗甜甜゛ 提交于 2019-12-01 17:51:24

问题


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?

So that I can run my function every 5 minutes or every day at 12 o'clock.

In Java there is the TimerTask, so I'm searching for something like that.


回答1:


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

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.

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.




回答2:


For the latest Rust nightly-version:

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


来源:https://stackoverflow.com/questions/28364995/is-there-a-way-to-schedule-a-task-at-a-specific-time-or-with-an-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!