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

后端 未结 2 1336
我寻月下人不归
我寻月下人不归 2021-01-18 05:47

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

相关标签:
2条回答
  • 2021-01-18 06:14

    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.

    0 讨论(0)
  • 2021-01-18 06:31

    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()
        }
    }
    
    0 讨论(0)
提交回复
热议问题