Add a sleep loop based on next action times clamping to a min/max range.

main
Tom Alexander 2 weeks ago
parent 2cbbe2428f
commit f1db62190a
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE

@ -68,9 +68,21 @@ impl DbHandle {
pub(crate) fn get_time_until_next_action(
&mut self,
) -> Result<Duration, Box<dyn std::error::Error>> {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_secs();
todo!()
let now = SystemTime::now();
let mut stmt = self.conn.prepare(
"WITH next_runs AS (SELECT next_run FROM global_action UNION SELECT next_run FROM local_action) SELECT next_run FROM next_runs ORDER BY next_run ASC",
)?;
let rows = stmt
.query_map(params![], |row| Ok(row.get(0)?))?
.collect::<Result<Vec<u64>, _>>()?;
if let Some(r) = rows.into_iter().next() {
let next_run = SystemTime::UNIX_EPOCH + Duration::from_secs(r);
if next_run <= now {
return Ok(Duration::from_secs(0));
} else {
return Ok(next_run.duration_since(now)?);
}
}
return Ok(Duration::from_secs(0));
}
}

@ -9,6 +9,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut db_conn: db::DbHandle = db::DbHandle::new(db_path)?;
loop {
thread::sleep(time::Duration::from_secs(300));
let time_until_next_action = db_conn.get_time_until_next_action()?;
let sleep_duration = std::cmp::min(
time::Duration::from_secs(60),
std::cmp::max(time_until_next_action, time::Duration::from_secs(300)),
);
println!("Sleeping for {} seconds.", sleep_duration.as_secs());
thread::sleep(sleep_duration);
}
}

Loading…
Cancel
Save