azalea_shell/service/
time.rs1use chrono::Timelike;
2use tokio::sync::broadcast;
3
4#[derive(Default, azalea_derive::StaticServiceManager)]
5pub struct Service {
6 minute: u32,
7 hour: u32,
8 interval_duration: std::time::Duration,
9}
10
11#[derive(Clone)]
12pub struct Init {
13 interval_duration: std::time::Duration,
14}
15
16impl Default for Init {
17 fn default() -> Self {
18 Self {
19 interval_duration: std::time::Duration::from_secs(1),
20 }
21 }
22}
23
24#[derive(Clone, Debug)]
25pub enum Output {
26 Second(chrono::DateTime<chrono::Local>),
27 Minute(chrono::DateTime<chrono::Local>),
28 Hour(chrono::DateTime<chrono::Local>),
29}
30
31impl azalea_service::Service for Service {
32 type Init = Init;
33 type Input = String;
34 type Event = ();
35 type Output = Output;
36
37 async fn new(
38 init: Self::Init,
39 _: flume::Sender<Self::Input>,
40 _: broadcast::Sender<Self::Output>,
41 ) -> Self {
42 Self {
43 interval_duration: init.interval_duration,
44 ..Default::default()
45 }
46 }
47
48 async fn message(
49 &mut self,
50 input: Self::Input,
51 _output_sender: &broadcast::Sender<Self::Output>,
52 ) {
53 println!("Received input {input:?}");
54 }
55
56 async fn event_generator(&mut self) -> Self::Event {
57 tokio::time::sleep(self.interval_duration).await;
58 }
59
60 async fn event_handler(
61 &mut self,
62 _event: Self::Event,
63 output_sender: &tokio::sync::broadcast::Sender<Self::Output>,
64 ) -> azalea_service::Result<()> {
65 let time = chrono::Local::now();
66
67 output_sender.send(Output::Second(time))?;
68
69 {
70 let minute = time.minute();
71
72 if self.minute != minute {
73 self.minute = minute;
74 output_sender.send(Output::Minute(time))?;
75
76 let hour = time.hour();
77 if self.hour != hour {
78 self.hour = hour;
79 output_sender.send(Output::Hour(time))?;
80 }
81 }
82 }
83
84 Ok(())
85 }
86}