Skip to main content

kimun_notes/components/
autosave_timer.rs

1use tokio::task::JoinHandle;
2
3use crate::components::events::{AppEvent, AppTx};
4
5pub struct AutosaveTimer {
6    handle: Option<JoinHandle<()>>,
7}
8
9impl Default for AutosaveTimer {
10    fn default() -> Self {
11        Self::new()
12    }
13}
14
15impl AutosaveTimer {
16    pub fn new() -> Self {
17        Self { handle: None }
18    }
19
20    /// Abort any running timer and start a new one that sends `AppEvent::Autosave`
21    /// every `interval_secs` seconds (skipping the first tick).
22    pub fn restart(&mut self, interval_secs: u64, tx: AppTx) {
23        self.stop();
24        self.handle = Some(tokio::spawn(async move {
25            let mut interval = tokio::time::interval(std::time::Duration::from_secs(interval_secs));
26            interval.tick().await; // skip immediate first tick
27            loop {
28                interval.tick().await;
29                if tx.send(AppEvent::Autosave).is_err() {
30                    break;
31                }
32            }
33        }));
34    }
35
36    pub fn stop(&mut self) {
37        if let Some(handle) = self.handle.take() {
38            handle.abort();
39        }
40    }
41}
42
43impl Drop for AutosaveTimer {
44    fn drop(&mut self) {
45        self.stop();
46    }
47}