openzeppelin_monitor/utils/cron_utils.rs
1//! Utility functions for working with cron schedules and time intervals
2//!
3//! This module provides helper functions for parsing and analyzing cron expressions,
4
5use chrono::Utc;
6use cron::Schedule;
7
8/// Calculates the time interval between two consecutive occurrences of a cron schedule
9///
10/// This function takes a cron expression and determines how many milliseconds will elapse
11/// between two consecutive runs of the schedule.
12///
13/// # Arguments
14///
15/// * `cron_schedule` - A string slice containing a valid cron expression (e.g., "0 0 * * *")
16///
17/// # Returns
18///
19/// * `Some(i64)` - The number of milliseconds between consecutive schedule runs
20/// * `None` - If the cron expression is invalid or if two consecutive occurrences cannot be
21/// determined
22pub fn get_cron_interval_ms(cron_schedule: &str) -> Option<i64> {
23 // Parse the cron schedule
24 let schedule = match cron_schedule.parse::<Schedule>() {
25 Ok(schedule) => schedule,
26 Err(_) => return None, // Return None if the cron string is invalid
27 };
28
29 // Get the current time
30 let now = Utc::now();
31
32 // Get the next two occurrences of the schedule
33 let mut occurrences = schedule.after(&now).take(2);
34
35 if let (Some(first), Some(second)) = (occurrences.next(), occurrences.next()) {
36 // Calculate the interval in milliseconds
37 let interval_ms = (second - first).num_milliseconds();
38 Some(interval_ms)
39 } else {
40 None // Return None if we cannot find two occurrences
41 }
42}