Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timer overrides previous #21

Merged
merged 1 commit into from
May 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading