From 18dd20db3c31ff8b6f8eca1b134128b7d32d3195 Mon Sep 17 00:00:00 2001 From: wrk Date: Thu, 1 Jun 2023 17:06:48 +0200 Subject: [PATCH] can't remember --- src/lib.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index b7949ae..1d9ab9c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,7 +13,7 @@ use std::{ net::ToSocketAddrs, path::Path, sync::Arc, - time::SystemTime, + time::{Duration, SystemTime}, }; use async_native_tls::TlsStream; @@ -171,7 +171,7 @@ pub struct Context { default_system: Option, invalid_system: Option, systems: HashMap, - tasks: Vec, + tasks: Vec<(Duration, StoredSystem)>, factory: Arc>, } @@ -310,12 +310,13 @@ impl Context { ) } - pub async fn run_tasks(&mut self, tx: mpsc::Sender) { - for mut task in std::mem::take(&mut self.tasks) { + pub async fn run_interval_tasks(&mut self, tx: mpsc::Sender) { + for (duration, mut task) in std::mem::take(&mut self.tasks) { let fact = self.factory.clone(); let task_tx = tx.clone(); tokio::spawn(async move { loop { + tokio::time::sleep(duration).await; let resp = task.run( &IrcPrefix { nick: "", @@ -406,13 +407,25 @@ impl Irc { self } + pub async fn add_interval_task System + Send + Sync + 'static>( + &mut self, + duration: Duration, + system: impl for<'a> IntoSystem, + ) -> &mut Self { + { + let mut context = self.context.write().await; + context.tasks.push((duration, Box::new(system.into_system()))); + } + self + } + pub async fn add_task System + Send + Sync + 'static>( &mut self, system: impl for<'a> IntoSystem, ) -> &mut Self { { let mut context = self.context.write().await; - context.tasks.push(Box::new(system.into_system())); + context.tasks.push((Duration::ZERO, Box::new(system.into_system()))); } self } @@ -542,7 +555,7 @@ impl Irc { { let mut context = self.context.write().await; context.register(); - context.run_tasks(tx).await; + context.run_interval_tasks(tx).await; } let stream = self.stream.take().unwrap();