Skip to main content

cron

Function cron 

Source
pub async fn cron<F, Fut>(event: ScheduledEvent, env: Env, run: F)
where F: FnOnce(Ctx, String) -> Fut, Fut: Future<Output = Result<()>>,
Expand description

Runs the app’s task for the Cron Trigger that fired; the Worker’s scheduled entry point.

Calls run(ctx, cron), where cron is the expression from a triggers.scheduled({ schedule }) entry of cloudflare.config.ts (UTC), and logs [ocre cron] <cron> done or [ocre cron] <cron> failed: <error>. Cloudflare does not retry a failed run; the next one comes at the next scheduled time, so enqueue jobs from the task for work that must not be lost. The Free plan allows 5 Cron Triggers per account and 10 ms of CPU per run: run several tasks from one cron, and move heavy work to jobs.

§Examples

ocre g schedule writes the entry point in src/lib.rs and run in src/schedules/mod.rs:

mod schedules {
    use ocre::{Ctx, Error, Result};

    pub async fn run(_ctx: Ctx, cron: String) -> Result<()> {
        match cron.as_str() {
            "0 3 * * *" => Ok(()), // nightly_cleanup
            other => Err(Error::internal(format!("no task for cron {other}"))),
        }
    }
}

#[worker::event(scheduled)]
async fn scheduled(event: worker::ScheduledEvent, env: worker::Env, _ctx: worker::ScheduleContext) {
    ocre::jobs::cron(event, env, schedules::run).await
}