Skip to content

Commit

Permalink
timer overrides previous (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulgb committed May 4, 2024
1 parent 65dd74e commit cb3d45d
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions stateroom-server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use stateroom::{
StateroomServiceFactory,
};
use std::{
sync::{atomic::AtomicU32, Arc},
sync::{atomic::AtomicU32, Arc, Mutex},
time::Duration,
};
use tokio::{
Expand All @@ -18,6 +18,7 @@ use tokio::{
pub struct ServerStateroomContext {
senders: Arc<DashMap<ClientId, Sender<Message>>>,
event_sender: Arc<Sender<Event>>,
timer_handle: Mutex<Option<tokio::task::JoinHandle<()>>>,
}

impl ServerStateroomContext {
Expand Down Expand Up @@ -61,12 +62,20 @@ impl StateroomContext for ServerStateroomContext {
}

fn set_timer(&self, ms_delay: u32) {
// TODO: setting the timer should replace the previous timer?
let sender = self.event_sender.clone();
tokio::spawn(async move {
let handle = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(ms_delay as u64)).await;
sender.send(Event::Timer).await.unwrap();
});

let mut c = self
.timer_handle
.lock()
.expect("timer handle lock poisoned");
if let Some(c) = c.take() {
c.abort();
}
*c = Some(handle);
}
}

Expand Down Expand Up @@ -98,6 +107,7 @@ impl ServerState {
let context = Arc::new(ServerStateroomContext {
senders: senders_.clone(),
event_sender: Arc::new(tx_),
timer_handle: Mutex::new(None),
});

let mut service = factory.build("", context.clone()).unwrap();
Expand Down

0 comments on commit cb3d45d

Please sign in to comment.