I am trying to implement a struct that keeps track of a global tick. In an effort to refactor I moved the timer
into the struct but now I am facing the issue of the timer guard
losing reference and thus the timer being dropped. My thought was to add the guard as struct member but I am not sure how to do this.
use timer;
use chrono;
use futures::Future;
use std::{process, thread};
use std::sync::{Arc, Mutex};
struct GlobalTime {
tick_count: Arc<Mutex<u64>>,
millis: Arc<Mutex<i64>>,
timer: timer::Timer,
guard: timer::Guard,
}
impl GlobalTime {
fn new() -> GlobalTime {
GlobalTime {
tick_count: Arc::new(Mutex::new(0)),
millis: Arc::new(Mutex::new(200)),
timer: timer::Timer::new(),
guard: ???, // what do I do here to init the guard??
}
}
fn tick(&self) {
*self.guard = {
let global_tick = self.tick_count.clone();
self.timer.schedule_repeating(
chrono::Duration::milliseconds(*self.millis.lock().unwrap()),
move || {
*global_tick.lock().unwrap() += 1;
println!("timer callback");
},
);
}
}
}