Skip to main content

larust_scheduler/
schedule.rs

1use chrono::{DateTime, Utc};
2use larust_core::AppError;
3use larust_orm::Backend;
4use sqlx::AnyPool;
5use std::future::Future;
6use std::pin::Pin;
7use std::str::FromStr;
8use std::time::Duration;
9
10type BoxedTask =
11    Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync>;
12
13struct Entry {
14    cron: cron::Schedule,
15    task: BoxedTask,
16    name: Option<String>,
17    /// See [`Schedule::on_one_server`].
18    on_one_server: bool,
19}
20
21/// A set of recurring tasks, declared once (typically inline in the
22/// generated app's own `schedule:work` branch - see `docs/ARCHITECTURE.md`'s
23/// "Scheduler" section) and handed to [`work`]. Consuming, `Self`-returning
24/// builder - the same "build a registry, then run it" shape as
25/// `larust_queue::JobRegistry`.
26#[must_use]
27pub struct Schedule {
28    entries: Vec<Entry>,
29}
30
31impl Default for Schedule {
32    fn default() -> Self {
33        Self::new()
34    }
35}
36
37impl Schedule {
38    pub fn new() -> Self {
39        Self {
40            entries: Vec::new(),
41        }
42    }
43
44    /// Escape hatch for any frequency the fluent methods below don't cover
45    /// directly (e.g. `"0 */5 * * * * *"` for every 5 minutes). Uses the
46    /// `cron` crate's own **7-field extended dialect** - seconds, minutes,
47    /// hours, day-of-month, month, day-of-week, year - not Laravel's
48    /// classic 5-field Unix cron format.
49    ///
50    /// Panics on an invalid expression: this is a startup-time
51    /// configuration mistake, not a runtime condition - the same
52    /// fail-loud-immediately precedent `larust_queue::JobRegistry::
53    /// register`'s duplicate-`JOB_TYPE` panic already establishes, rather
54    /// than surfacing as a confusing "the scheduler silently never runs
55    /// this task" bug discovered much later.
56    pub fn cron<F, Fut>(mut self, expr: &str, task: F) -> Self
57    where
58        F: Fn() -> Fut + Send + Sync + 'static,
59        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
60    {
61        let parsed = cron::Schedule::from_str(expr).unwrap_or_else(|error| {
62            panic!(
63                "invalid cron expression {expr:?}: {error} -- Schedule::cron uses the `cron` \
64                 crate's 7-field dialect (sec min hour day-of-month month day-of-week year), \
65                 not the classic 5-field Unix cron format"
66            )
67        });
68        self.entries.push(Entry {
69            cron: parsed,
70            task: Box::new(move || Box::pin(task())),
71            name: None,
72            on_one_server: false,
73        });
74        self
75    }
76
77    /// Names the most recently registered task - same "applies to
78    /// whatever was just registered" convention `larust_http::Router::
79    /// name` already uses for routes. Required before
80    /// [`Self::on_one_server`]: a task closure has no identity of its own
81    /// to derive a stable cross-process lock key from (unlike
82    /// `larust_queue::Job::JOB_TYPE`, a compile-time constant on a real
83    /// type) - matching Laravel's own requirement that a closure-based
84    /// scheduled task be named before `->onOneServer()` can be used.
85    ///
86    /// # Panics
87    /// If called before registering any task at all.
88    pub fn name(mut self, name: impl Into<String>) -> Self {
89        self.entries
90            .last_mut()
91            .expect("Schedule::name called before registering any task")
92            .name = Some(name.into());
93        self
94    }
95
96    /// Marks the most recently registered task so at most one `xr
97    /// schedule:work` process actually runs it for each due occurrence,
98    /// even when multiple processes are running against the same app
99    /// (e.g. a rolling deploy's brief overlap) - Laravel's own
100    /// `->onOneServer()`. Backed by a small self-bootstrapping
101    /// `scheduler_locks` table (no migration file, same lazy `CREATE
102    /// TABLE IF NOT EXISTS` idiom `larust-notifications`'s `ensure_table`
103    /// establishes): the first process whose claim attempt for a given
104    /// `(task name, due instant)` pair wins an `INSERT` actually runs the
105    /// task; every other process racing for the same pair loses the
106    /// `INSERT` to a unique-constraint violation and skips it - the same
107    /// "claim by winning a race-safe write, treat losing as a normal
108    /// no-op" shape `larust_queue::sql_worker::claim_next` already uses
109    /// for job claiming, not an advisory-lock/session-primitive approach
110    /// (SQLite has no equivalent to Postgres's `pg_advisory_lock`/MySQL's
111    /// `GET_LOCK()` at all, so a plain row claim is the only mechanism
112    /// portable across every backend this framework supports).
113    ///
114    /// A task NOT marked this way keeps today's original behavior
115    /// unchanged: whichever process's own tick lands on a due instant
116    /// just runs it, no coordination, no database dependency added -
117    /// still correct for a genuinely single-process deployment, which
118    /// remains the default.
119    ///
120    /// A claim-attempt database error is treated as "don't run this
121    /// occurrence," not "run it anyway": the documented failure mode
122    /// this mechanism exists to prevent (silent duplicate side effects)
123    /// is worse than an occasional missed run under a database outage.
124    ///
125    /// # Panics
126    /// If the most recently registered task has no name yet (see
127    /// [`Self::name`]) - the same fail-loud-at-registration-time
128    /// precedent every other `Schedule` builder method already
129    /// establishes for a startup-time configuration mistake.
130    pub fn on_one_server(mut self) -> Self {
131        let entry = self
132            .entries
133            .last_mut()
134            .expect("Schedule::on_one_server called before registering any task");
135        assert!(
136            entry.name.is_some(),
137            "Schedule::on_one_server requires .name(...) first -- a task closure has no \
138             identity of its own to derive a cross-process lock key from"
139        );
140        entry.on_one_server = true;
141        self
142    }
143
144    /// Runs `task` once every minute, at second 0.
145    pub fn every_minute<F, Fut>(self, task: F) -> Self
146    where
147        F: Fn() -> Fut + Send + Sync + 'static,
148        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
149    {
150        self.cron("0 * * * * * *", task)
151    }
152
153    /// Runs `task` once every hour, on the hour.
154    pub fn hourly<F, Fut>(self, task: F) -> Self
155    where
156        F: Fn() -> Fut + Send + Sync + 'static,
157        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
158    {
159        self.cron("0 0 * * * * *", task)
160    }
161
162    /// Runs `task` once a day, at midnight UTC.
163    pub fn daily<F, Fut>(self, task: F) -> Self
164    where
165        F: Fn() -> Fut + Send + Sync + 'static,
166        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
167    {
168        self.cron("0 0 0 * * * *", task)
169    }
170
171    /// Runs `task` once a day at the given `"HH:MM"` UTC time. Panics on a
172    /// malformed or out-of-range value - same fail-loud-at-startup
173    /// precedent as [`Self::cron`]'s invalid-expression panic.
174    pub fn daily_at<F, Fut>(self, time: &str, task: F) -> Self
175    where
176        F: Fn() -> Fut + Send + Sync + 'static,
177        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
178    {
179        let (hour, minute) = parse_hh_mm(time);
180        self.cron(&format!("0 {minute} {hour} * * * *"), task)
181    }
182
183    /// Runs `task` once a week, Sunday at midnight UTC.
184    pub fn weekly<F, Fut>(self, task: F) -> Self
185    where
186        F: Fn() -> Fut + Send + Sync + 'static,
187        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
188    {
189        self.cron("0 0 0 * * Sun *", task)
190    }
191
192    /// Runs `task` once a month, on the 1st at midnight UTC.
193    pub fn monthly<F, Fut>(self, task: F) -> Self
194    where
195        F: Fn() -> Fut + Send + Sync + 'static,
196        Fut: Future<Output = Result<(), AppError>> + Send + 'static,
197    {
198        self.cron("0 0 0 1 * * *", task)
199    }
200}
201
202fn parse_hh_mm(time: &str) -> (u32, u32) {
203    let (hour_str, minute_str) = time.split_once(':').unwrap_or_else(|| {
204        panic!("invalid time {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
205    });
206    let hour: u32 = hour_str.parse().unwrap_or_else(|_| {
207        panic!("invalid hour in {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
208    });
209    let minute: u32 = minute_str.parse().unwrap_or_else(|_| {
210        panic!("invalid minute in {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
211    });
212    assert!(
213        hour < 24,
214        "hour out of range in {time:?} for Schedule::daily_at -- expected 00-23"
215    );
216    assert!(
217        minute < 60,
218        "minute out of range in {time:?} for Schedule::daily_at -- expected 00-59"
219    );
220    (hour, minute)
221}
222
223/// How long a claimed `scheduler_locks` row is kept before a later claim
224/// attempt for the same task prunes it - bounds the table's growth for a
225/// frequent `.on_one_server()` task (e.g. `.every_minute()`) rather than
226/// letting it accumulate one row per occurrence forever. Pruning is
227/// scoped to the task's own rows (uses the composite primary key's
228/// leading column) and runs opportunistically, right before that same
229/// task's next claim attempt - there is no separate maintenance job.
230const LOCK_RETENTION_SECS: i64 = 7 * 24 * 60 * 60;
231
232/// Creates the `scheduler_locks` table if it doesn't exist yet - no
233/// migration file, plain `CREATE TABLE IF NOT EXISTS`, matching
234/// `larust-notifications`'s `ensure_table`. Deliberately **not**
235/// memoized behind a process-wide "already ensured" flag the way
236/// `larust_queue::ensure_tables` is: that memoization only pays off for
237/// a hot-path call, and this only runs when an `.on_one_server()` task
238/// is actually due (rare - hourly/daily by far the common case), while a
239/// memoized flag would risk the exact regression `larust-notifications`'s
240/// own doc comment describes - a flag set by one test's database
241/// surviving into a later test against a *different* one.
242async fn ensure_lock_table(pool: &AnyPool) -> Result<(), AppError> {
243    let create_table = match larust_orm::backend() {
244        Backend::Sqlite => {
245            "CREATE TABLE IF NOT EXISTS scheduler_locks (\
246                task_name TEXT NOT NULL, \
247                scheduled_for_unix INTEGER NOT NULL, \
248                PRIMARY KEY (task_name, scheduled_for_unix)\
249             )"
250        }
251        // `VARCHAR`, not `TEXT` - same `sqlx::Any`-driver decode gap
252        // `larust_queue::ensure_tables`'s own doc comment documents in
253        // full for MySQL specifically (Postgres/SQLite have no such
254        // gap).
255        Backend::MySql => {
256            "CREATE TABLE IF NOT EXISTS scheduler_locks (\
257                task_name VARCHAR(255) NOT NULL, \
258                scheduled_for_unix BIGINT NOT NULL, \
259                PRIMARY KEY (task_name, scheduled_for_unix)\
260             )"
261        }
262        Backend::Postgres => {
263            "CREATE TABLE IF NOT EXISTS scheduler_locks (\
264                task_name TEXT NOT NULL, \
265                scheduled_for_unix BIGINT NOT NULL, \
266                PRIMARY KEY (task_name, scheduled_for_unix)\
267             )"
268        }
269    };
270    sqlx::query(create_table)
271        .execute(pool)
272        .await
273        .map_err(|source| AppError::Internal(Box::new(source)))?;
274    Ok(())
275}
276
277/// Attempts to claim `task_name`'s occurrence due at `at` - `Ok(true)` if
278/// this call won the claim (the caller should run the task), `Ok(false)`
279/// if another process already claimed this exact `(task_name, at)` pair
280/// first (the caller should skip it). See [`Schedule::on_one_server`]'s
281/// own doc comment for the full design rationale.
282async fn claim(task_name: &str, at: DateTime<Utc>) -> Result<bool, AppError> {
283    let pool = larust_orm::pool()?;
284    ensure_lock_table(pool).await?;
285
286    let backend = larust_orm::backend();
287    let scheduled_for = at.timestamp();
288
289    let prune_sql = format!(
290        "DELETE FROM scheduler_locks WHERE task_name = {} AND scheduled_for_unix < {}",
291        larust_orm::placeholder(backend, 1),
292        larust_orm::placeholder(backend, 2),
293    );
294    sqlx::query(&prune_sql)
295        .bind(task_name)
296        .bind(scheduled_for - LOCK_RETENTION_SECS)
297        .execute(pool)
298        .await
299        .map_err(|source| AppError::Internal(Box::new(source)))?;
300
301    let claim_sql = format!(
302        "INSERT INTO scheduler_locks (task_name, scheduled_for_unix) VALUES ({}, {})",
303        larust_orm::placeholder(backend, 1),
304        larust_orm::placeholder(backend, 2),
305    );
306    match sqlx::query(&claim_sql)
307        .bind(task_name)
308        .bind(scheduled_for)
309        .execute(pool)
310        .await
311    {
312        Ok(_) => Ok(true),
313        // A losing claimer hits this exact task+occurrence's composite
314        // primary key already existing - the normal "someone else got
315        // there first" outcome, not an error.
316        Err(sqlx::Error::Database(database)) if database.is_unique_violation() => Ok(false),
317        Err(source) => Err(AppError::Internal(Box::new(source))),
318    }
319}
320
321/// Runs every task in `schedule` whose cron expression matches `at`,
322/// sequentially, in registration order. Not `pub` - directly unit-testable
323/// against a fixed instant, no real clock/sleep involved, the same role
324/// `larust_queue::worker::process_next` plays for the queue worker.
325///
326/// Sequential, not concurrent: a slow task delays a same-tick sibling
327/// (and the next tick's own check, since `work()` awaits this whole call
328/// before ticking again) - but this also means a task can never overlap
329/// *with itself* across ticks for free, a safer default than
330/// concurrent-by-default would be without an explicit
331/// `withoutOverlapping()`-equivalent. A task returning `Err` is logged and
332/// does not stop the others due this tick, matching both
333/// `larust_events::dispatch`'s "a listener that can fail should log its
334/// own error rather than short-circuit the others" and the queue worker's
335/// "a failed job is recorded, the loop continues."
336async fn run_due(schedule: &Schedule, at: DateTime<Utc>) {
337    for entry in &schedule.entries {
338        if !entry.cron.includes(at) {
339            continue;
340        }
341
342        if entry.on_one_server {
343            // Guaranteed `Some` by `Schedule::on_one_server`'s own
344            // registration-time assertion.
345            let name = entry.name.as_deref().unwrap();
346            match claim(name, at).await {
347                Ok(true) => {}
348                Ok(false) => {
349                    tracing::info!(
350                        task = name,
351                        "scheduled task already claimed by another process this occurrence, \
352                         skipping"
353                    );
354                    continue;
355                }
356                Err(error) => {
357                    tracing::error!(
358                        task = name,
359                        %error,
360                        "failed to claim scheduled task lock, skipping this occurrence"
361                    );
362                    continue;
363                }
364            }
365        }
366
367        match (entry.task)().await {
368            Ok(()) => {
369                tracing::info!(cron = entry.cron.source(), name = ?entry.name, "scheduled task ran");
370            }
371            Err(error) => {
372                tracing::error!(
373                    cron = entry.cron.source(),
374                    name = ?entry.name,
375                    %error,
376                    "scheduled task failed"
377                );
378            }
379        }
380    }
381}
382
383const TICK_INTERVAL: Duration = Duration::from_secs(1);
384
385/// Runs forever, checking every registered task against the current time
386/// once a second (matching seconds - the `cron` crate's own native
387/// precision, even though every fluent method above only offers
388/// minute-or-coarser granularity) and running whichever are due. No direct
389/// test exists for this function - the same posture `larust_queue::
390/// worker::work`'s own doc comment takes; only `run_due` is tested.
391///
392/// Uses `MissedTickBehavior::Skip`: if a task blocks this loop for, say, 90
393/// seconds, anything due during that window silently does not run - it is
394/// **not** queued up and burst-fired afterward. This matches Laravel's own
395/// `schedule:run` behavior, not just a Rust-idiom default: Laravel's own
396/// scheduler is invoked once a minute by an external cron entry with no
397/// catch-up mechanism either, if that invocation's own process is still
398/// busy.
399///
400/// **Running more than one process against the same app is safe only for
401/// tasks explicitly marked [`Schedule::on_one_server`].** Any other task
402/// still has no claim/lock step at all - it just checks an in-memory
403/// `Schedule` against the wall clock, so two `xr schedule:work` processes
404/// watching the same app both run every one of *those* due tasks, every
405/// time, silently duplicating side effects (e.g. sending the same email
406/// twice). This is the same shape Laravel itself shipped: its scheduler
407/// ran single-process-only for a long time before `->onOneServer()`
408/// existed, and even now a task must opt in explicitly - nothing makes
409/// this safe by default, in either framework, because a coordinated
410/// claim costs a database round trip a genuinely single-process
411/// deployment (still the common case) shouldn't have to pay for tasks
412/// that don't need it.
413pub async fn work(schedule: Schedule) -> Result<(), AppError> {
414    let mut interval = tokio::time::interval(TICK_INTERVAL);
415    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
416    tracing::info!("scheduler worker started");
417    loop {
418        interval.tick().await;
419        run_due(&schedule, Utc::now()).await;
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use chrono::TimeZone;
427    use std::sync::atomic::{AtomicUsize, Ordering};
428    use std::sync::Arc;
429
430    fn assert_send_sync<T: Send + Sync>() {}
431
432    #[test]
433    fn schedule_is_send_and_sync() {
434        assert_send_sync::<Schedule>();
435    }
436
437    #[test]
438    fn every_minute_produces_the_expected_cron_source() {
439        let schedule = Schedule::new().every_minute(|| async { Ok(()) });
440        assert_eq!(schedule.entries[0].cron.source(), "0 * * * * * *");
441    }
442
443    #[test]
444    fn hourly_produces_the_expected_cron_source() {
445        let schedule = Schedule::new().hourly(|| async { Ok(()) });
446        assert_eq!(schedule.entries[0].cron.source(), "0 0 * * * * *");
447    }
448
449    #[test]
450    fn daily_produces_the_expected_cron_source() {
451        let schedule = Schedule::new().daily(|| async { Ok(()) });
452        assert_eq!(schedule.entries[0].cron.source(), "0 0 0 * * * *");
453    }
454
455    #[test]
456    fn weekly_produces_the_expected_cron_source() {
457        let schedule = Schedule::new().weekly(|| async { Ok(()) });
458        assert_eq!(schedule.entries[0].cron.source(), "0 0 0 * * Sun *");
459    }
460
461    #[test]
462    fn monthly_produces_the_expected_cron_source() {
463        let schedule = Schedule::new().monthly(|| async { Ok(()) });
464        assert_eq!(schedule.entries[0].cron.source(), "0 0 0 1 * * *");
465    }
466
467    #[test]
468    fn daily_at_parses_hh_mm_into_the_expected_cron_source() {
469        let schedule = Schedule::new().daily_at("13:07", || async { Ok(()) });
470        assert_eq!(schedule.entries[0].cron.source(), "0 7 13 * * * *");
471    }
472
473    #[test]
474    #[should_panic(expected = "invalid time")]
475    fn daily_at_panics_on_a_malformed_time() {
476        let _ = Schedule::new().daily_at("not-a-time", || async { Ok(()) });
477    }
478
479    #[test]
480    #[should_panic(expected = "hour out of range")]
481    fn daily_at_panics_on_an_out_of_range_hour() {
482        let _ = Schedule::new().daily_at("24:00", || async { Ok(()) });
483    }
484
485    #[test]
486    #[should_panic(expected = "invalid cron expression")]
487    fn cron_panics_on_an_invalid_expression() {
488        let _ = Schedule::new().cron("not a cron expression", || async { Ok(()) });
489    }
490
491    #[tokio::test]
492    async fn run_due_fires_a_task_exactly_at_a_matching_instant_not_a_neighboring_one() {
493        let matching_calls = Arc::new(AtomicUsize::new(0));
494        let calls = Arc::clone(&matching_calls);
495        let schedule = Schedule::new().cron("0 30 9 * * * *", move || {
496            let calls = Arc::clone(&calls);
497            async move {
498                calls.fetch_add(1, Ordering::SeqCst);
499                Ok(())
500            }
501        });
502
503        let matching = Utc.with_ymd_and_hms(2026, 8, 15, 9, 30, 0).unwrap();
504        let not_matching = Utc.with_ymd_and_hms(2026, 8, 15, 9, 31, 0).unwrap();
505
506        run_due(&schedule, not_matching).await;
507        assert_eq!(matching_calls.load(Ordering::SeqCst), 0);
508
509        run_due(&schedule, matching).await;
510        assert_eq!(matching_calls.load(Ordering::SeqCst), 1);
511    }
512
513    #[tokio::test]
514    async fn a_failing_task_does_not_block_a_same_tick_sibling() {
515        let good_calls = Arc::new(AtomicUsize::new(0));
516        let calls = Arc::clone(&good_calls);
517
518        let schedule = Schedule::new()
519            .cron("0 0 12 * * * *", || async {
520                Err(AppError::Internal(Box::new(std::io::Error::other(
521                    "deliberate test failure",
522                ))))
523            })
524            .cron("0 0 12 * * * *", move || {
525                let calls = Arc::clone(&calls);
526                async move {
527                    calls.fetch_add(1, Ordering::SeqCst);
528                    Ok(())
529                }
530            });
531
532        let at = Utc.with_ymd_and_hms(2026, 8, 15, 12, 0, 0).unwrap();
533        run_due(&schedule, at).await;
534
535        assert_eq!(
536            good_calls.load(Ordering::SeqCst),
537            1,
538            "the second task should still have run despite the first failing"
539        );
540    }
541
542    #[test]
543    #[should_panic(expected = "requires .name(...) first")]
544    fn on_one_server_panics_without_a_name_first() {
545        let _ = Schedule::new().daily(|| async { Ok(()) }).on_one_server();
546    }
547
548    #[test]
549    #[should_panic(expected = "called before registering any task")]
550    fn name_panics_before_any_task_is_registered() {
551        let _ = Schedule::new().name("too-early");
552    }
553
554    #[test]
555    fn name_and_on_one_server_apply_to_the_most_recently_registered_task() {
556        let schedule = Schedule::new()
557            .daily(|| async { Ok(()) })
558            .hourly(|| async { Ok(()) })
559            .name("hourly-task")
560            .on_one_server();
561
562        assert_eq!(schedule.entries[0].name, None);
563        assert!(!schedule.entries[0].on_one_server);
564        assert_eq!(schedule.entries[1].name.as_deref(), Some("hourly-task"));
565        assert!(schedule.entries[1].on_one_server);
566    }
567
568    // Connects once (`larust_orm::connect` errors on a second call in the
569    // same process - see `larust_queue::sql_worker`'s own `connect_test_db`
570    // for the identical constraint) and exercises every `claim`/`.
571    // on_one_server` scenario sequentially against that one database,
572    // matching `sql_worker.rs`'s own established workaround for this
573    // limitation rather than trying to split into several independently
574    // DB-connected test functions.
575    #[tokio::test]
576    async fn on_one_server_claims_exactly_once_per_task_and_occurrence() {
577        let dir = tempfile::tempdir().unwrap().keep();
578        let database_url = format!("sqlite://{}/test.sqlite", dir.display());
579        larust_orm::connect(&database_url).await.unwrap();
580
581        let at = Utc.with_ymd_and_hms(2026, 8, 15, 9, 30, 0).unwrap();
582        let later = Utc.with_ymd_and_hms(2026, 8, 15, 10, 30, 0).unwrap();
583
584        // First claimer for a given (task, occurrence) wins.
585        assert!(claim("report-task", at).await.unwrap());
586        // A second claim attempt for the exact same (task, occurrence)
587        // loses - this is the whole mechanism: a losing claimer must see
588        // `Ok(false)`, not an error, since losing a race is the expected,
589        // routine outcome for every process but the first.
590        assert!(!claim("report-task", at).await.unwrap());
591        // A different task at the same instant is unaffected - the lock
592        // key is the pair, not just the timestamp.
593        assert!(claim("other-task", at).await.unwrap());
594        // The same task at a different occurrence is unaffected either -
595        // the lock key is the pair, not just the task name.
596        assert!(claim("report-task", later).await.unwrap());
597
598        // End-to-end through `run_due`: an `.on_one_server()` task whose
599        // occurrence is already claimed does not run; one that hasn't
600        // been claimed yet does.
601        let already_claimed_calls = Arc::new(AtomicUsize::new(0));
602        let calls = Arc::clone(&already_claimed_calls);
603        let unclaimed_calls = Arc::new(AtomicUsize::new(0));
604        let calls2 = Arc::clone(&unclaimed_calls);
605
606        let schedule = Schedule::new()
607            .cron("0 0 11 * * * *", move || {
608                let calls = Arc::clone(&calls);
609                async move {
610                    calls.fetch_add(1, Ordering::SeqCst);
611                    Ok(())
612                }
613            })
614            .name("report-task")
615            .on_one_server()
616            .cron("0 0 11 * * * *", move || {
617                let calls = Arc::clone(&calls2);
618                async move {
619                    calls.fetch_add(1, Ordering::SeqCst);
620                    Ok(())
621                }
622            })
623            .name("fresh-task")
624            .on_one_server();
625
626        let eleven = Utc.with_ymd_and_hms(2026, 8, 15, 11, 0, 0).unwrap();
627        claim("report-task", eleven).await.unwrap(); // pre-claim by "another process"
628        run_due(&schedule, eleven).await;
629
630        assert_eq!(
631            already_claimed_calls.load(Ordering::SeqCst),
632            0,
633            "a task whose occurrence was already claimed elsewhere must not run"
634        );
635        assert_eq!(
636            unclaimed_calls.load(Ordering::SeqCst),
637            1,
638            "a task whose occurrence was not yet claimed must run exactly once"
639        );
640    }
641}