updating the alarm will now also update the cron schedule

This commit is contained in:
2026-03-03 16:02:23 +01:00
parent 5a818bae56
commit 024a212fe2
2 changed files with 26 additions and 7 deletions

Binary file not shown.

View File

@@ -1,4 +1,5 @@
use std::i32;
use std::collections::HashMap;
use std::{i32, usize};
use std::sync::{Arc, Mutex};
use chrono::{DateTime, Local, Timelike, Utc};
@@ -6,7 +7,7 @@ use cron_tab::Cron;
use sea_orm::ActiveValue::Set;
use sea_orm::{ActiveModelTrait, DatabaseConnection, DbErr};
use crate::dao::alarm::{create_alarm, get_alarm, get_alarms};
use crate::dao::alarm::{self, create_alarm, get_alarm, get_alarms};
use crate::model;
use crate::ringer::Ringer;
use crate::types::Alarm;
@@ -16,6 +17,7 @@ pub struct Scheduler {
ringer: Arc<Mutex<dyn Ringer>>,
cron: Arc<Mutex<Cron<Local>>>,
db: Arc<DatabaseConnection>,
cron_jobs: Arc<Mutex<HashMap<i32, usize>>>
}
impl Scheduler {
@@ -28,10 +30,11 @@ impl Scheduler {
ringer,
cron,
db,
cron_jobs: Arc::new(Mutex::new(HashMap::new()))
}
}
pub fn schedule(&self, cron_schedule: &str) -> Result<(), String> {
pub fn schedule(&self, cron_schedule: &str) -> Result<usize, String> {
let ringer = self.ringer.clone();
let cron = self.cron.clone();
@@ -45,8 +48,8 @@ impl Scheduler {
}
});
job_result.expect("Faild to add job");
Ok(())
Ok(job_result.expect("Faild to add job"))
}
pub async fn add_alarm(&self, time: DateTime<Utc>, title: String) -> Result<Alarm, String> {
@@ -56,7 +59,8 @@ impl Scheduler {
.await
.map_err(|e| e.to_string())?;
self.schedule(&cron_schedule).map_err(|e| e.to_string())?;
let job_id = self.schedule(&cron_schedule).map_err(|e| e.to_string())?;
self.cron_jobs.lock().expect("Failed to lock cron_jobs").insert(created_alarm.id, job_id);
println!("Added alarm {}", cron_schedule);
Ok(created_alarm.into())
@@ -94,6 +98,8 @@ impl Scheduler {
let updated_alarm = active_alarm.update(&*self.db).await?;
self.reregister_alarm(updated_alarm.clone().into());
return Ok(Some(updated_alarm.into()));
}
@@ -126,7 +132,8 @@ impl Scheduler {
let scheduling_result = self.schedule(&cron_schedule);
match scheduling_result {
Ok(_) => {
Ok(job_id) => {
self.cron_jobs.lock().expect("Failed to lock cron_jobs").insert(alarm.id, job_id);
println!("Registered alarm {}", cron_schedule);
},
Err(e) => {
@@ -139,4 +146,16 @@ impl Scheduler {
let time = time.with_timezone(&Local);
format!("{} {} {} * * *", "*", time.minute(), time.hour())
}
fn reregister_alarm(&self, alarm: Alarm) {
let job_id = self.cron_jobs.lock().expect("Failed to lock cron_jobs")
.remove(&alarm.id);
if let Some(job_id) = job_id {
self.cron.lock().expect("Failed to lock cron handler").remove(job_id);
}
let new_job_id = self.schedule(&self.construct_cron_schedule(alarm.time)).expect("failed to register alarm");
self.cron_jobs.lock().expect("Failed to lock cron_jobs").insert(alarm.id, new_job_id);
}
}