Skip to main content

encore/
cron.rs

1//! Scheduled cron jobs that invoke an HTTP endpoint on your service.
2//!
3//! Declare a job as a module-level `static` with its target path and schedule:
4//!
5//! ```ignore
6//! use encore::cron::{Job, Schedule};
7//!
8//! /// Removes sessions that have been inactive for a month.
9//! static CLEANUP: Job =
10//!     Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).title("Nightly cleanup");
11//!
12//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"));
13//! ```
14//!
15//! When the job is due, Encore sends a `POST` request to the configured path on
16//! the declaring service. Register your route using [`Job::path`] so the route
17//! and cron declaration stay in sync:
18//!
19//! ```ignore
20//! let app = Router::new().route(CLEANUP.path(), post(cleanup));
21//! ```
22//!
23//! # Execution headers
24//!
25//! Each cron request includes an idempotency key in [`IDEMPOTENCY_KEY_HEADER`].
26//! This ID remains the same across retries of the same scheduled run, so
27//! handlers that must avoid duplicate work can deduplicate on it:
28//!
29//! ```ignore
30//! async fn cleanup(headers: HeaderMap) -> StatusCode {
31//!     let key = headers.get(encore::cron::IDEMPOTENCY_KEY_HEADER);
32//!     // ...
33//! }
34//! ```
35//!
36//! [`TRIGGER_HEADER`] indicates whether the job was triggered on schedule or
37//! manually. Gateways strip both headers from external client requests so only
38//! Encore can set them.
39//!
40//! # Running locally and in tests
41//!
42//! By default, cron jobs only run on schedule in deployed environments. To run
43//! a job on schedule during local development as well, enable
44//! [`Job::run_in_local`]:
45//!
46//! ```ignore
47//! static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
48//!     .run_in_local(true);
49//! ```
50//!
51//! Locally, scheduled jobs run while an `encore run` session is active, and
52//! developers can toggle local scheduling per checkout regardless of the
53//! declaration. Cron jobs are not scheduled under `encore test`. Run a job
54//! immediately with `encore cron trigger <name>` (which includes both headers),
55//! or send a `POST` request directly to its handler path.
56
57/// Header containing the idempotency key for a cron execution.
58///
59/// The value stays the same if Encore retries the same run. See the
60/// [module documentation](self).
61pub const IDEMPOTENCY_KEY_HEADER: &str = "x-encore-cron-execution";
62
63/// Header indicating why a cron job ran: `"scheduled"` for a scheduled run, or
64/// `"manual"` when triggered on demand.
65pub const TRIGGER_HEADER: &str = "x-encore-cron-trigger";
66
67/// Schedule defining when a [`Job`] runs.
68///
69/// Must be written inline with a string literal where the job is declared so
70/// Encore can parse it statically.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum Schedule {
73    /// Runs according to a five-field [cron expression] (minute, hour, day of
74    /// month, month, day of week) in UTC. For example, `"0 4 * * *"` runs daily
75    /// at 04:00 UTC, and `"0 9 * * 1"` runs Mondays at 09:00 UTC.
76    ///
77    /// [cron expression]: https://en.wikipedia.org/wiki/Cron#Cron_expression
78    Cron(&'static str),
79    /// Runs at a fixed interval specified in hours and minutes, such as `"30m"`,
80    /// `"6h"`, or `"1h30m"`.
81    ///
82    /// Runs are aligned to midnight UTC each day (for example, `"6h"` runs at
83    /// 00:00, 06:00, 12:00, and 18:00 UTC). The interval must be a whole number
84    /// of minutes that divides 24 hours evenly (for example, `"45m"` and `"8h"`
85    /// are valid, whereas `"50m"` and `"7h"` are not).
86    Every(&'static str),
87}
88
89/// A declared cron job. See the [module documentation](self).
90///
91/// Declare as a module-level `static` with an app-wide unique name using
92/// lowercase letters, digits, and dashes.
93#[derive(Debug)]
94pub struct Job {
95    name: &'static str,
96    path: &'static str,
97    schedule: Schedule,
98    title: Option<&'static str>,
99    run_in_local: bool,
100}
101
102impl Job {
103    /// Declares a cron job named `name` that sends a `POST` request to `path` on
104    /// the declaring service according to `schedule`.
105    ///
106    /// `path` must start with `/`. Both `name` and `path` must be string
107    /// literals, and `schedule` must be written inline so Encore can parse them
108    /// statically.
109    pub const fn new(name: &'static str, path: &'static str, schedule: Schedule) -> Self {
110        Self {
111            name,
112            path,
113            schedule,
114            title: None,
115            run_in_local: false,
116        }
117    }
118
119    /// Sets a human-readable display title shown in the dashboard instead of
120    /// the job's identifier.
121    pub const fn title(mut self, title: &'static str) -> Self {
122        self.title = Some(title);
123        self
124    }
125
126    /// Controls whether the job runs on schedule during local development while
127    /// an `encore run` session is active.
128    ///
129    /// Defaults to `false`. Developers can still override this setting per
130    /// checkout. Deployed environments always schedule the job regardless of
131    /// this setting.
132    ///
133    /// ```no_run
134    /// use encore::cron::{Job, Schedule};
135    ///
136    /// static REFRESH: Job = Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m"))
137    ///     .run_in_local(true);
138    /// ```
139    pub const fn run_in_local(mut self, local: bool) -> Self {
140        self.run_in_local = local;
141        self
142    }
143
144    /// Attaches a key/value tag to the job (for example, `.tag("data", "pci")`)
145    /// for policy and governance tooling.
146    ///
147    /// Call once per tag with unique keys. Both `key` and `value` must be string
148    /// literals so Encore can parse them statically. Keys must start with a
149    /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
150    /// not start with `encore` (reserved for Encore's own tags). Values use the
151    /// same character set or may be empty. Each key and value is at most 63
152    /// characters, and a job may have at most 32 tags.
153    ///
154    /// ```no_run
155    /// use encore::cron::{Job, Schedule};
156    ///
157    /// static CLEANUP: Job =
158    ///     Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *")).tag("team", "ops");
159    /// ```
160    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
161        self
162    }
163
164    /// Returns the job's name.
165    pub const fn name(&self) -> &'static str {
166        self.name
167    }
168
169    /// Returns the HTTP path that Encore invokes when the job runs.
170    pub const fn path(&self) -> &'static str {
171        self.path
172    }
173
174    /// Returns the job's schedule.
175    pub const fn schedule(&self) -> Schedule {
176        self.schedule
177    }
178
179    /// Returns whether the job is configured to run on schedule locally (see
180    /// [`run_in_local`](Self::run_in_local)).
181    pub const fn runs_in_local(&self) -> bool {
182        self.run_in_local
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    static CLEANUP: Job = Job::new("cleanup", "/internal/cleanup", Schedule::Cron("0 4 * * *"))
191        .title("Nightly cleanup");
192    static REFRESH: Job =
193        Job::new("refresh-rates", "/internal/rates", Schedule::Every("30m")).run_in_local(true);
194
195    #[test]
196    fn a_job_is_declared_in_a_static() {
197        assert_eq!(CLEANUP.name(), "cleanup");
198        assert_eq!(CLEANUP.path(), "/internal/cleanup");
199        assert_eq!(CLEANUP.schedule(), Schedule::Cron("0 4 * * *"));
200        assert_eq!(CLEANUP.title, Some("Nightly cleanup"));
201
202        assert_eq!(REFRESH.schedule(), Schedule::Every("30m"));
203        assert_eq!(REFRESH.title, None);
204    }
205
206    #[test]
207    fn a_job_runs_locally_only_when_it_says_so() {
208        assert!(!CLEANUP.runs_in_local());
209        assert!(REFRESH.runs_in_local());
210    }
211}