How do i pause and restart timers from another thread?

In the example program below, if I wanted to be able to control an individual timer (eg pause ticker2, but leave ticker1 running) from outside of the thread, what would be the best way to do this in rust, I was thnking of just using a global variable but I figure there is a proper rust way to do it?

use crossbeam_channel::{select, tick};
use std::time::Duration;
use std::thread;

fn main() {
  start_timers();

  //code to pause/restart one of the timers???
}

fn start_timers() {
  let ticker1 = tick(Duration::from_secs(1));
  let ticker2 = tick(Duration::from_secs(5));

  thread::spawn(move || {
    loop {
      select! {
        recv(ticker1) -> _ => foo(),
        recv(ticker2) -> _ => foo2()
      }
    }
  });
}

fn foo() {
  println!("bar");
}

fn foo2() {
  println!("bar2");
}

You would need to add a third channel that the main thread can use to tell the timer thread that the timer should be paused. Then the timer thread can manually pause it.

1 Like

thanks alice, thats exactly the solution i arrived at!

Good to see I was on the right track!

Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.