cbsk_timer/timer/
simple_timer.rs

1use std::sync::atomic::{AtomicBool, Ordering};
2use std::time::Duration;
3
4/// simple timer tasks
5pub struct SimpleTimer {
6    /// timer name
7    pub name: String,
8    /// whether to end the task
9    pub(crate) end: AtomicBool,
10    /// task
11    pub task: Box<dyn Fn(&Self)>,
12    /// task loop interval
13    pub interval: Duration,
14}
15
16/// support timer
17impl super::Timer for SimpleTimer {
18    fn name(&self) -> &str {
19        self.name.as_str()
20    }
21
22    fn run(&self) {
23        (self.task)(self);
24    }
25
26    fn ended(&self) -> bool {
27        self.end.load(Ordering::Acquire)
28    }
29
30    fn interval(&self) -> Option<Duration> {
31        Some(self.interval)
32    }
33}
34
35/// custom method
36impl SimpleTimer {
37    /// create simple loop task
38    pub fn new(name: impl Into<String>, interval: Duration, task: impl Fn(&Self) + 'static) -> Self {
39        Self {
40            name: name.into(),
41            end: AtomicBool::new(false),
42            task: Box::new(task),
43            interval,
44        }
45    }
46
47    /// notification timer task needs to end
48    pub fn task_end(&self) {
49        self.end.store(true, Ordering::Release)
50    }
51}