Schedule
In-process cron and interval jobs — declared as methods on any provider, activated by the schedule adapter that lists it.
A scheduled job is a method on any #[injectable] provider, tagged with
#[every], #[cron], or #[after] inside a #[scheduled] impl block.
The decorator brings ScheduleModule to the schedule adapter listing the
provider, which attaches the scheduler at boot, so an app importing the adapter
runs its ticks.
Triggers are validated at compile time (string literals, the IANA
timezone included) or at boot (CronExpression presets); a bad preset
fails the boot naming the offending job.
nest-rs-schedule builds on croner — the framework
wraps it for cron expression parsing (5/6/7-field), with
jiff for the optional IANA timezone.
Install
Section titled “Install”cargo add nest-rs --features scheduleEvery replica of an app runs its own scheduler, so four pods fire a job four times. A job that must fire once across them claims each occurrence in Redis — a second feature on the same page:
cargo add nest-rs --features redis-scheduleA first scheduled method
Section titled “A first scheduled method”A regular #[injectable] service with one decorated method. The #[scheduled]
attribute marks the impl block; #[every("5s")] marks the method as a
recurring job.
use std::sync::Arc;
use anyhow::Result;use nest_rs::core::injectable;use nest_rs::schedule::{CronExpression, scheduled};
use crate::audio::{AUDIO_QUEUE, AudioConfig, AudioService};
#[injectable]pub struct AudioTasks { #[inject] svc: Arc<AudioService>, #[inject] config: Arc<AudioConfig>,}
#[scheduled]impl AudioTasks { #[every("5s", replicas = "one")] async fn enqueue_transcode(&self) -> Result<()> { if !self.config.seeds() { return Ok(()); } self.svc.seed_and_enqueue().await?; Ok(()) } // …}#[injectable]makesAudioTasksa regular DI provider — same#[inject]shape as any other service.#[scheduled]on the impl block orchestrates the per-method trigger attributes and submits one cron entry per decorated method.#[every("5s", replicas = "one")]runs the method on a fixed interval, once per occurrence across the app’s replicas. Every replica of the API runs this scheduler, and the method stores a source object and enqueues a transcode of it — work the deployment wants done once, which three replicas left at the default would do three times. So each occurrence is claimed through the app’s occurrence lock and fires on the one replica that wins it; see Firing once across replicas. A failure returnsErr; it is logged and the schedule continues — one failed run never stops the job.- The cron method is thin. Its only job is to decide when and
what payload (here a synthetic file id). The plumbing — the object
store, the
Jobshandle, the queue — lives insideAudioService::seed_and_enqueue, which ends in the sameenqueue_transcodethe HTTP producer calls, so there is exactly one place where the “enqueue an audio job” decision lives.
Several methods on the same provider
Section titled “Several methods on the same provider”This is the pattern the framework is built for. A single #[injectable]
owns the deps once, and as many decorated methods as you need share them.
Mix triggers freely:
#[scheduled]impl AudioTasks { #[every("5s", replicas = "one")] async fn enqueue_transcode(&self) -> Result<()> { // … }
#[after("3s")] async fn warmup_on_boot(&self) -> Result<()> { tracing::info!( target: crate::audio::TARGET, phase = "warmup", "audio pipeline ready to enqueue", ); Ok(()) }
#[cron(CronExpression::EVERY_MINUTE, replicas = "each")] async fn heartbeat(&self) -> Result<()> { tracing::info!( target: crate::audio::TARGET, queue = AUDIO_QUEUE, "audio producer heartbeat", ); Ok(()) }}Three cron entries land in the scheduler — AudioTasks::enqueue_transcode,
AudioTasks::warmup_on_boot, AudioTasks::heartbeat — all pointing at the
same AudioTasks instance. Same Arc<AudioService>, three triggers, no
ceremony. Each method calls into the service or logs; none of them
build a queue payload or reach for a connection.
Each one declares how many replicas fire it, by what it does. The seed
is work the deployment does once, so replicas = "one". The heartbeat says
this process is alive, which is only true if every process says it, so
replicas = "each" — the default, written out so the decision is read
rather than inferred. And #[after] fires once per process by construction:
it is a process’s own warm-up, and takes no replicas at all.
Triggers
Section titled “Triggers”| Form | Meaning |
|---|---|
#[every("30s")] |
Fixed interval (ms, s, m, h) |
#[after("10s")] |
One-shot — runs N after boot, then never |
#[cron("0 */5 * * * *")] |
6-field cron expression |
#[cron(CronExpression::EVERY_5_SECONDS)] |
Named preset (validated at boot) |
#[cron("0 9 * * MON", tz = "Europe/Paris")] |
Cron + named timezone (default UTC) |
#[every("5m", replicas = "one")] |
Once per occurrence across replicas — see Firing once across replicas |
#[every("1h", timeout = "30m")] |
A run lasting past 30 minutes is cut — see How long a run lasts |
A cron string literal and a tz name are validated at compile time; a
CronExpression constant when the scheduler configures at boot, which fails
naming the job and the offending value. An invalid trigger is never
silently skipped.
A tz name is read from one database, the IANA time zone database bundled
with jiff (jiff-tzdb): the compiler checks the name against it and the
scheduler reads the zone’s rules from it, never from the host’s
/usr/share/zoneinfo, so an image built FROM scratch needs nothing installed.
That copy is your lockfile’s — cargo update -p jiff-tzdb brings the latest
IANA release — and the job’s boot line names the release it read
(tzdb="2026f").
Wire it in
Section titled “Wire it in”The provider goes in its feature module like any other #[injectable]:
use nest_rs::core::module;
use super::tasks::AudioTasks;use crate::audio::AudioModule;
#[module(imports = [AudioModule], providers = [AudioTasks])]pub struct AudioScheduleModule;The module imports AudioModule because AudioTasks injects
Arc<AudioService>; the AudioConfig it injects too loads itself. Forget
the import and the access graph fails the
boot with a clear message naming AudioService as the missing
dependency — the same Rust-visibility rule every other adapter follows.
#[scheduled] brings ScheduleModule, which runs its ticks: the scheduler
attaches once however many hosts bring it.
The app imports the adapter and, since the seed fires once across replicas,
the occurrence lock it claims through: RedisScheduleModule, which imports
the RedisModule opening its connection. The lock is a backend the app chooses, so it
stays at the root; leave it out and the boot fails, naming
AudioTasks::enqueue_transcode and the binding to import.
use nest_rs::core::{GlobalInterceptors, module};// …use nest_rs::redis::{RedisQueueModule, RedisScheduleModule};// …use features::audio::{AudioHttpModule, AudioScheduleModule};// …
#[module( imports = [ // … RedisQueueModule, // … RedisScheduleModule, // … AudioHttpModule, AudioScheduleModule, ], // …)]pub struct ApiModule;main carries no transport at all — every transport (HttpModule and
ScheduleModule here, QueueModule in the worker) comes with the host that
serves on it and attaches itself at boot.
An app ticks the methods its own modules reach, and no others: an
HTTP-only app that links the features crate imports no schedule adapter, so
it never runs a worker’s schedule.
Run it
Section titled “Run it”$ nestrs run dev api… INFO nest_rs::app: transport attached transport="schedule" INFO nest_rs::schedule: mounted host="AudioTasks" method="enqueue_transcode" trigger="every" interval_ms=5000 replicas="one" key="features::AudioTasks::enqueue_transcode" INFO nest_rs::schedule: mounted host="AudioTasks" method="warmup_on_boot" trigger="after" delay_ms=3000 replicas="each" INFO nest_rs::schedule: mounted host="AudioTasks" method="heartbeat" trigger="cron" timezone="UTC" replicas="each" INFO features::audio: audio pipeline ready to enqueue phase="warmup" trace_id=01a015a91d527cb1b9d15a8ba7fe8846 span_id=bd824ae7eb1f9e7a INFO nest_rs::operation: schedule.tick host="AudioTasks" method="warmup_on_boot" replicas="each" outcome="ok" duration_ms=0.302 trace_id=01a015a91d527cb1b9d15a8ba7fe8846 span_id=bd824ae7eb1f9e7aDEBUG features::audio: enqueued transcode job queue="audio" trace_id=01a015a9252076e399f736a97ae90784 span_id=052e261668035200 INFO nest_rs::operation: schedule.tick host="AudioTasks" method="enqueue_transcode" replicas="one" occurrence=1787069800000 outcome="ok" duration_ms=101.901 trace_id=01a015a9252076e399f736a97ae90784 span_id=052e261668035200The scheduler logs one mounted line per job at boot, its trigger the
decorator that declared it (every, after or cron), then one
schedule.tick line at
info on nest_rs::operation for every tick it fires, whatever the tick came
to — its host, method, replicas, outcome and duration_ms, and the
occurrence a job firing once claimed. It is the same operation line every edge
files once per unit of work, so nest_rs::operation=off in the log filter
silences it with the others. A failed run adds one scheduled job failed line
at error; the schedule keeps ticking.
A bad cron literal never reaches boot — it fails cargo build:
$ nestrs run dev apierror: #[cron]: "every monday" is not a cron expression: Invalid pattern: Pattern must have between 5 and 7 fields. --> crates/features/src/audio/schedule/tasks.rs:40:12 |40 | #[cron("every monday")] | ^^^^^^^^^^^^^^What bounds and surrounds a run — its deadline, the layers around it, its transaction, its trace and its turn at shutdown — is Running a tick.
Reference
Section titled “Reference”crates/features/src/audio/schedule/tasks.rs— the canonical multi-method exemplar.crates/features/src/notifications/schedule/tasks.rs— a job firing once across the worker’s replicas, andapps/worker/src/module.rs, which binds its lock.crates/nest-rs-schedule/—#[scheduled],ScheduleModule,Scheduler,CronExpression,Trigger,Replicas, and theOccurrenceLockport a job firing once claims through.crates/nest-rs-redis/src/schedule/—RedisScheduleModuleandRedisOccurrenceLock, the Redis binding of that port.
Going further
Section titled “Going further”- Queue — pair a scheduled producer with a durable consumer for distributed work.
- OpenTelemetry — every schedule event is targeted on
nest_rs::schedule, carryinghostandmethodfields (plusinterval_ms/delay_ms/timezone/tzdbon the boot lines, and thekeya job firing once claims under).