Skip to content

Improve cron_event_handler to support passing custom functions to be executed at specific times #205

@dmitrypol

Description

@dmitrypol

Need to improve this rough code to enable passing multiple functions to run at the same schedule and not use specific hz of 100 ms

static CRONTAB: LazyLock<HashMap<&'static str, fn(&Context)>> = LazyLock::new(|| {
    let mut map = HashMap::new();
    map.insert(
        "*/5 * * * * * *".to_string()
        my_custom_fn as fn(&Context),
    );
    map
});

#[cron_event_handler]
fn cron_event_handler(ctx: &Context, _hz: u64) {
    for (expression, function) in CRONTAB.iter() {
        // using unwrap to explicitly crash if schedule is invalid
        let schedule = Schedule::from_str(expression).unwrap();
        let next_time = schedule.upcoming(Utc).next().unwrap_or_default();
        let now = Utc::now();
        // 100 milliseconds as hz 10 per second by default, look for serverCron()
        if next_time.timestamp_millis() <= now.timestamp_millis() + 100 {
            function(ctx);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions