Task Scheduling
- Introduction
- Defining schedules
- Running the scheduler
- Frequencies and constraints
- Preventing overlap
- Running on one runner
- Running tasks in order
- Sub-minute tasks
- Task output
- Task hooks
- Events
- Scheduling from packages
- Testing
Introduction
Many applications have recurring work that runs on a schedule rather than in response to an HTTP request, such as sending a weekly digest or pruning stale records every night. In the past, you may have managed a separate cron entry on your server for each task, keeping your schedule outside source control and forcing you to SSH into the server whenever it changed.
dust-framework's scheduler lets you express your entire schedule fluently in application code alongside the commands it runs. Your schedule lives in source control and deploys with your app, while your server only needs a single cron entry running schedule:run every minute.
Defining schedules
New applications define their schedule in src/console/mod.rs using the #[schedule::tasks] attribute, which dust-framework discovers automatically. For example, this schedule calls an async function every day at midnight to prune a table:
use dust::db;use dust::schedule::{self, Schedule};#[schedule::tasks]fn schedule(schedule: &mut Schedule) { schedule.call(prune_recent_users).daily();}async fn prune_recent_users() -> dust::Result<()> { db::table("recent_users").delete().await?; Ok(())}Scheduled callbacks can be async functions or closures returning () or dust::Result<()>. They may also accept injected services via Inject<T> and config sections via Section<T>, resolved fresh on each run inside a new application context:
use dust::config::Section;use dust::container::Inject;use dust::schedule::{self, Schedule};use crate::config::billing::Billing;use crate::services::BillingService;#[schedule::tasks]fn schedule(schedule: &mut Schedule) { schedule.call(sync_invoices).hourly();}async fn sync_invoices( billing: Inject<BillingService>, config: Section<Billing>,) -> dust::Result<()> { billing.sync_due_invoices(&config.account_id).await?; Ok(())}When your schedule definition itself depends on configuration, the schedule function may also accept &Config as a second parameter:
use dust::config::Config;use dust::schedule::{self, Schedule};use crate::config::billing::Billing;#[schedule::tasks]fn schedule(schedule: &mut Schedule, config: &Config) { let billing = config.section::<Billing>(); if billing.sync_enabled { schedule.call(sync_invoices).daily_at(&billing.sync_at); }}Scheduling commands and programs
In addition to callbacks, you can schedule console commands and external programs. command runs one of your application's commands in a fresh process. Write the command line as you would in a terminal; the scheduler splits arguments using shell-style quoting without invoking a shell, so variables such as $HOME and globs such as * are passed literally:
schedule.command("emails:send Taylor --force").daily_at("08:00");When an argument is computed at runtime, such as a value from configuration, append it with args so spaces, quotes, and $ require no escaping. Use exec to schedule external executables with args as well:
use dust::config::Config;use dust::schedule::{self, Schedule};#[schedule::tasks]fn schedule(schedule: &mut Schedule, config: &Config) { schedule.command("backup:run --disk").args([&config.filesystems.default]).daily(); schedule.exec("node").args(["scripts/report.js"]).hourly();}To run a command through a shell with pipes or redirects, use shell:
schedule.shell("node scripts/report.js | gzip > storage/report.gz").daily();Only pass trusted command strings to shell, never user input. All scheduled processes execute with your application's base path as their working directory.
Scheduling queued jobs
Because callbacks run inside the schedule:run process, a deploy or crash can interrupt long-running work. For tasks that take more than a few seconds, schedule a queued job with job so a queue worker processes it in the background:
use dust::schedule::{self, Schedule, Weekday};use crate::jobs::SendWeeklyDigest;#[schedule::tasks]fn schedule(schedule: &mut Schedule) { schedule .job(SendWeeklyDigest) .weekly_on(Weekday::Monday, "08:00");}Use on_queue and on_connection to override the job's default queue or queue connection:
schedule .job(SendWeeklyDigest) .on_connection("redis") .on_queue("emails") .weekly_on(Weekday::Monday, "08:00");Running the scheduler
The schedule:run command evaluates your schedule and runs every task due in the current minute. With the cron feature, dust install adds the schedule:run cron for you, and you may add it on its own at any time:
dust schedule:setupThat cron runs your application's binary every minute at second zero from the application's folder, and leaves an existing schedule:run cron alone. If you don't use dust's cron, add a single entry to your server's cron yourself:
* * * * * cd /path/to/your-app && ./your-app schedule:run >> /dev/null 2>&1Due tasks run concurrently, and schedule:run waits for all of them to finish before exiting. If a task fails, dust-framework reports the error to your error handler and continues running the remaining tasks. The scheduler does not backfill missed minutes after downtime.
[!NOTE] When deploying on DUST Cloud, Cloud can manage and run the scheduler for your application automatically without requiring a manual cron entry.
Running the scheduler locally
During local development, you don't need to configure cron. Run schedule:work instead to invoke schedule:run at the start of every minute until you stop it:
dust schedule:workListing tasks
Run schedule:list to view every scheduled task along with its cron expression and next run time in UTC. Pass -v to include full command lines, or --json for machine-readable output:
dust schedule:listCommands
| Command | Does |
|---|---|
schedule:run |
Runs every task due in the current minute, then exits |
schedule:work |
Calls schedule:run at the start of every minute until stopped |
schedule:setup |
Adds the schedule:run cron and leaves an existing one alone |
schedule:list |
Prints each task with its expression and next run time |
schedule:interrupt |
Tells running schedulers to stop after their current tasks |
schedule:clear-cache |
Clears the overlap and one-runner locks |
schedule:run is the only command your server's cron needs. The others are for development, inspection, or recovery.
Frequencies and constraints
By default, scheduled tasks run every minute, and all frequencies are evaluated in UTC. You can customize the schedule using any of these frequency methods:
| Method | Schedule |
|---|---|
cron("*/5 8-17 * * MON-FRI") |
A custom five-field cron expression |
every_second(), every_five_seconds(), every_thirty_seconds(), and others |
Several times within each minute, as sub-minute tasks describes |
every_minute() |
Every minute |
every_two_minutes(), every_five_minutes(), every_fifteen_minutes(), and others |
Every few minutes |
hourly(), hourly_at(17) |
Every hour, at minute zero or the given minute |
every_two_hours(), every_six_hours(), and others |
Every few hours, counting from midnight |
daily(), daily_at("13:00") |
Every day, at midnight or the given time |
twice_daily(1, 13), twice_daily_at(1, 13, 15) |
Every day at the two given hours, at minute zero or the given minute |
weekly(), weekly_on(Weekday::Monday, "08:00") |
Sunday at midnight, or the given weekday and time |
monthly(), monthly_on(4, "15:00") |
The first day at midnight, or the given day and time |
days_of_month([1, 10, 20]) |
The given days of the month, at midnight |
twice_monthly(1, 16, "13:00") |
Two days of the month, at the given time |
last_day_of_month("15:00") |
The month's last day, at the given time |
quarterly(), quarterly_on(4, "14:00") |
The first day of January, April, July, and October at midnight, or the given day and time of those months |
yearly(), yearly_on(6, 1, "17:00") |
January 1st at midnight, or the given month, day, and time |
You may narrow a frequency to certain days of the week with weekdays, weekends, or mondays through sundays. days([Weekday::Sunday, Weekday::Wednesday]) picks specific weekdays, and at("13:00") sets the time of day. This task runs every Monday at 13:00:
schedule.command("reports:generate").weekly().mondays().at("13:00");Additional constraints
Use between to run a task only within a specific time window, or unless_between to skip it during that window. Both endpoints are inclusive, and windows may span midnight such as 23:00 to 04:00:
schedule.command("emails:send").hourly().between("08:00", "17:00");Use environments to restrict a task to specific environments matching APP_ENV:
schedule.command("emails:send") .daily() .environments(["staging", "production"]);Use when to run a task only when an async predicate returns true, or skip to suppress it when the predicate returns true. Predicates return bool or dust::Result<bool> and may accept Inject<T> services and Section<T> config sections. When multiple when predicates are attached, all of them must return true:
schedule .command("emails:send") .daily() .skip(async || { let today = dust::now(); today.month() == 12 && today.day() == 25 });Timezones
The scheduler evaluates all times in UTC. If a task must follow a local timezone across daylight saving transitions, such as sending a report at 8:00 AM Chicago time all year, schedule both candidate UTC hours and check the local hour in a when predicate:
schedule .command("reports:send") .twice_daily(13, 14) .when(async || -> dust::Result<bool> { Ok(dust::now().in_tz("America/Chicago")?.hour() == 8) });Preventing overlap
By default, scheduled tasks run even if the previous instance is still executing. To skip a run while an earlier one is still in progress, chain without_overlapping:
schedule.command("emails:send").every_minute().without_overlapping();without_overlapping is especially useful for tasks whose duration varies unpredictably. It acquires a lock in your cache store while the task runs. Because each schedule:run invocation runs in a separate process, configure a shared cache store such as database or redis; the default memory store is local to a single process and cannot coordinate across invocations.
If your default cache store is not shared, call use_cache to select a shared store for all scheduled tasks. The database store requires its lock table:
#[schedule::tasks]fn schedule(schedule: &mut Schedule) { schedule.use_cache("database"); schedule.command("emails:send").every_minute().without_overlapping();}Overlap locks expire automatically after 24 hours so a crashed process cannot block a task indefinitely. To set a shorter expiration, call without_overlapping_for with a duration longer than the task's expected maximum runtime:
use dust::time::ToSpan;schedule .call(prune_recent_users) .name("prune-recent-users") .every_minute() .without_overlapping_for(10.minutes());Callbacks using without_overlapping must specify a name so the scheduler can derive a stable lock key.
If a crash leaves an overlap lock behind, run schedule:clear-cache to clear all overlap locks. Use it only for crash recovery, since it also releases locks held by tasks that are still running:
dust schedule:clear-cacheRunning on one runner
If your application runs schedule:run across multiple servers, every server will execute every due task unless coordinated. For example, three servers running the scheduler would each generate your Friday evening report. Chain on_one_runner so only one server executes the task for a given minute:
schedule.command("reports:generate") .fridays() .at("17:00") .on_one_runner();The first server to reach the task acquires a cache lock for that minute, causing all other servers to skip it. All servers must share the same cache store as described in preventing overlap.
Because on_one_runner only deduplicates within a single minute, combine it with without_overlapping for tasks that may run longer than one minute.
Naming tasks
Servers identify tasks by their name, schedule, and command. Callbacks using on_one_runner require an explicit name because Rust function type names can vary across builds. When scheduling the same callback multiple times with different arguments, assign each registration a unique name:
for account in [42, 84] { schedule .call(move || async move { tracing::info!(account, "Checking account") }) .name(format!("check-account-{account}")) .hourly() .on_one_runner();}Running tasks in order
Due tasks start in the order they are defined and execute concurrently, so they may finish in any order. When subsequent tasks must wait for an earlier task to complete before starting, mark that task blocking:
schedule.command("reports:generate").hourly();schedule.command("accounts:reconcile").hourly().blocking();schedule.command("statements:send").hourly();Here, statements:send waits for accounts:reconcile to finish, while accounts:reconcile runs concurrently with reports:generate. If several steps must always execute strictly in sequence, combine them into a single callback or command.
Sub-minute tasks
Although cron triggers schedule:run once per minute, you can schedule tasks to run as frequently as every second:
schedule.command("orders:sync").every_second();When a sub-minute task is due, schedule:run stays active for the remainder of the minute and repeats the task on schedule. Additional constraints still apply at the minute level, so every_ten_seconds().weekdays() runs only on weekdays. If a previous iteration is still running when the next interval arrives, the scheduler skips that tick. Keep sub-minute tasks lightweight by dispatching queued jobs for heavy work, and combine them with on_one_runner across multiple servers.
For recurring work scoped to each server process or queue worker, such as flushing in-memory buffers, use a tick instead. Ticks run inside serve and queue:work and do not require cron.
Interrupting sub-minute tasks
Because schedule:run keeps running for the rest of the minute when a sub-minute task is due, a run that started before you deployed keeps repeating its tasks with your previous build until the minute ends. To stop it sooner, add the schedule:interrupt command to your deployment script, after the new build is in place:
./your-app schedule:interruptEach schedule:run in progress, on every server, notices the signal within a second. It starts no more repeats, waits for the tasks already running to finish, and exits. The next minute's schedule:run uses your new build. The signal travels through the same cache store as the scheduler's overlap locks, so that store must be one every process shares, such as database or redis, rather than memory.
Task output
By default, the scheduler discards console output from scheduled commands and external processes. To capture that output to a file, use send_output_to to overwrite the file or append_output_to to append to it (making sure the target directory exists first):
schedule .command("emails:send") .daily() .send_output_to("storage/logs/emails.log");schedule .command("emails:send") .daily() .append_output_to("storage/logs/emails.log");Log messages and reported errors from your application's scheduled commands still go to your configured log channels automatically, even without send_output_to. Scheduled closures have no process output to capture, so use logging inside closures as well.
Task hooks
Use before, after, on_success, and on_failure to execute code before or after a scheduled task runs. A task counts as failed if it returns an error, panics, or exits with a nonzero status code. If a before hook fails, the task itself does not run. Post-run hooks receive an Event<TaskResult> with the task's error, exit_code, duration, and output:
use dust::event::Event;use dust::schedule::TaskResult;schedule .command("emails:send") .daily() .before(async || tracing::info!("Sending emails")) .on_success(async |result: Event<TaskResult>| { tracing::info!(duration = %result.duration, "Sent emails"); }) .on_failure(async |result: Event<TaskResult>| { tracing::error!(error = ?result.error, "Couldn't send emails"); });When a task captures output with send_output_to or append_output_to, result.output contains a TaskOutput with text() and bytes() to read the file into memory, stream() to stream chunks to file storage without buffering the whole file, and path() to pass the file path directly to an email attachment:
use dust::event::Event;use dust::schedule::TaskResult;use dust::storage;schedule .command("reports:generate") .daily() .send_output_to("storage/logs/report.log") .on_success(async |result: Event<TaskResult>| -> dust::Result<()> { if let Some(output) = &result.output { let stream = output.stream().await?; storage::disk("s3")?.write_stream("logs/report.log", stream).await?; } Ok(()) });Inside an after hook, call result.succeeded() to check whether the task finished cleanly. Like scheduled callbacks, hooks may accept Inject<T> services and Section<T> config sections.
Events
The scheduler dispatches events in dust::schedule::events throughout each task's lifecycle. Listening for ScheduledTaskFailed lets you centralize alerting for all scheduled task failures:
| Event | Dispatched when |
|---|---|
ScheduledTaskStarting |
A task starts. |
ScheduledTaskFinished |
A task and its hooks finish, regardless of outcome. |
ScheduledTaskSkipped |
A due task is skipped due to a when or skip predicate, another runner, or an overlap lock. |
ScheduledTaskFailed |
A task, predicate, lock, or hook fails. |
Define a listener in src/listeners/ to monitor task execution or alert on failures:
use dust::event::{Event, listener};use dust::schedule::events::ScheduledTaskFailed;#[listener]pub async fn log_failed_task(event: Event<ScheduledTaskFailed>) { tracing::error!( task = %event.result.task.name, error = ?event.result.error, "Scheduled task failed", );}Scheduling from packages
Packages can register their own scheduled tasks, such as a nightly cleanup or morning report, inside their service provider's register method:
use dust::container::Registrar;use dust::foundation::ServiceProvider;impl ServiceProvider for ReportsProvider { fn register(&self, app: &mut Registrar) { app.commands().add::<GenerateReport>(); app.schedule().command("reports:generate").daily_at("06:00"); }}Here, ReportsProvider is the package's service provider and GenerateReport is its command struct.
Testing
The scheduler only decides when your tasks run, so your tests don't need to run it. Each task is a command, a job, or an async function, and you may test each of those directly. For each one, write the test you'd write if nothing scheduled it.
An inline closure in schedule can't be called from a test, so move the work you pass to call into a named pub async fn and schedule it by name. For example, make prune_recent_users from Defining schedules pub in src/console/mod.rs, and declare pub mod console; in src/lib.rs so integration tests can import it:
// src/console/mod.rsuse dust::db;use dust::schedule::{self, Schedule};#[schedule::tasks]fn schedule(schedule: &mut Schedule) { schedule.call(prune_recent_users).daily();}pub async fn prune_recent_users() -> dust::Result<()> { db::table("recent_users").delete().await?; Ok(())}Your test then calls the function directly inside #[dust::test], which runs inside the test's application and database:
// tests/scheduling.rsuse dust::db;use dust::testing::prelude::*;#[dust::test]async fn pruning_recent_users_empties_the_table(app: Application) -> dust::Result<()> { db::table("recent_users") .insert(db::values! { name: "Taylor" }) .await?; app::console::prune_recent_users().await?; app.assert_database_count("recent_users", 0).await; Ok(())}To test a scheduled command, run its command line with app.command, as the console guide's section on testing commands shows. To test a scheduled job, run one attempt of it with app.job, as the queue guide's section on testing a job shows:
app.command("emails:send Taylor --force").await.assert_successful();app.job(SendWeeklyDigest).await.assert_succeeded();If your task's work depends on the date, such as a report that covers the previous month, travel to that date before you call the function, command, or job. To check when each task runs, run schedule:list, which shows every task's next run time.