1use teaql_tool_core::{Result, TeaQLToolError};
2use cron::Schedule;
3use std::str::FromStr;
4use chrono::Utc;
5use std::time::Duration;
6
7#[derive(Debug, Clone)]
8pub struct CronTool;
9
10impl CronTool {
11 pub fn new() -> Self { Self }
12
13 pub fn schedule<F>(&self, cron_expr: &str, mut callback: F) -> Result<()>
15 where
16 F: FnMut() + Send + 'static,
17 {
18 let schedule = Schedule::from_str(cron_expr).map_err(|e| TeaQLToolError::ParseError(e.to_string()))?;
19 for datetime in schedule.upcoming(Utc) {
20 let now = Utc::now();
21 if let Ok(duration) = (datetime - now).to_std() {
22 std::thread::sleep(duration);
23 callback();
24 }
25 }
26 Ok(())
27 }
28}
29
30impl Default for CronTool {
31 fn default() -> Self { Self::new() }
32}