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.
Laravel'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 Laravel discovers automatically. For example, this schedule calls an async function every day at midnight to prune a table:
1use laravel::db;2use laravel::schedule::{self, Schedule};34#[schedule::tasks]5fn schedule(schedule: &mut Schedule) {6 schedule.call(prune_recent_users).daily();7}89async fn prune_recent_users() -> laravel::Result<()> {10 db::table("recent_users").delete().await?;1112 Ok(())13}1use laravel::db;2use laravel::schedule::{self, Schedule};34#[schedule::tasks]5fn schedule(schedule: &mut Schedule) {6 schedule.call(prune_recent_users).daily();7}89async fn prune_recent_users() -> laravel::Result<()> {10 db::table("recent_users").delete().await?;1112 Ok(())13}
Scheduled callbacks can be async functions or closures returning () or laravel::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:
1use laravel::config::Section;2use laravel::container::Inject;3use laravel::schedule::{self, Schedule};45use crate::config::billing::Billing;6use crate::services::BillingService;78#[schedule::tasks]9fn schedule(schedule: &mut Schedule) {10 schedule.call(sync_invoices).hourly();11}1213async fn sync_invoices(14 billing: Inject<BillingService>,15 config: Section<Billing>,16) -> laravel::Result<()> {17 billing.sync_due_invoices(&config.account_id).await?;1819 Ok(())20}1use laravel::config::Section;2use laravel::container::Inject;3use laravel::schedule::{self, Schedule};45use crate::config::billing::Billing;6use crate::services::BillingService;78#[schedule::tasks]9fn schedule(schedule: &mut Schedule) {10 schedule.call(sync_invoices).hourly();11}1213async fn sync_invoices(14 billing: Inject<BillingService>,15 config: Section<Billing>,16) -> laravel::Result<()> {17 billing.sync_due_invoices(&config.account_id).await?;1819 Ok(())20}
When your schedule definition itself depends on configuration, the schedule function may also accept &Config as a second parameter:
1use laravel::config::Config;2use laravel::schedule::{self, Schedule};34use crate::config::billing::Billing;56#[schedule::tasks]7fn schedule(schedule: &mut Schedule, config: &Config) {8 let billing = config.section::<Billing>();910 if billing.sync_enabled {11 schedule.call(sync_invoices).daily_at(&billing.sync_at);12 }13}1use laravel::config::Config;2use laravel::schedule::{self, Schedule};34use crate::config::billing::Billing;56#[schedule::tasks]7fn schedule(schedule: &mut Schedule, config: &Config) {8 let billing = config.section::<Billing>();910 if billing.sync_enabled {11 schedule.call(sync_invoices).daily_at(&billing.sync_at);12 }13}
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:
1schedule.command("emails:send Taylor --force").daily_at("08:00");1schedule.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:
1use laravel::config::Config;2use laravel::schedule::{self, Schedule};34#[schedule::tasks]5fn schedule(schedule: &mut Schedule, config: &Config) {6 schedule.command("backup:run --disk").args([&config.filesystems.default]).daily();78 schedule.exec("node").args(["scripts/report.js"]).hourly();9}1use laravel::config::Config;2use laravel::schedule::{self, Schedule};34#[schedule::tasks]5fn schedule(schedule: &mut Schedule, config: &Config) {6 schedule.command("backup:run --disk").args([&config.filesystems.default]).daily();78 schedule.exec("node").args(["scripts/report.js"]).hourly();9}
To run a command through a shell with pipes or redirects, use shell:
1schedule.shell("node scripts/report.js | gzip > storage/report.gz").daily();1schedule.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:
1use laravel::schedule::{self, Schedule, Weekday};23use crate::jobs::SendWeeklyDigest;45#[schedule::tasks]6fn schedule(schedule: &mut Schedule) {7 schedule8 .job(SendWeeklyDigest)9 .weekly_on(Weekday::Monday, "08:00");10}1use laravel::schedule::{self, Schedule, Weekday};23use crate::jobs::SendWeeklyDigest;45#[schedule::tasks]6fn schedule(schedule: &mut Schedule) {7 schedule8 .job(SendWeeklyDigest)9 .weekly_on(Weekday::Monday, "08:00");10}
Use on_queue and on_connection to override the job's default queue or queue connection:
1schedule2 .job(SendWeeklyDigest)3 .on_connection("redis")4 .on_queue("emails")5 .weekly_on(Weekday::Monday, "08:00");1schedule2 .job(SendWeeklyDigest)3 .on_connection("redis")4 .on_queue("emails")5 .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. On your server, add a single cron entry invoking your compiled binary every minute:
1* * * * * cd /path/to/your-app && ./your-app schedule:run >> /dev/null 2>&11* * * * * cd /path/to/your-app && ./your-app schedule:run >> /dev/null 2>&1
Due tasks run concurrently, and schedule:run waits for all of them to finish before exiting. If a task fails, Laravel reports the error to your error handler and continues running the remaining tasks. The scheduler does not backfill missed minutes after downtime.
When deploying on Laravel 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:
1laravel schedule:work1laravel schedule:work
Listing 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:
1laravel schedule:list1laravel schedule:list
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,, twice_daily_at(1, |
Every day at the two given hours, at minute zero or the given minute |
weekly(), weekly_on(Weekday::Monday, |
Sunday at midnight, or the given weekday and time |
monthly(), monthly_on(4, |
The first day at midnight, or the given day and time |
days_of_month([1, |
The given days of the month, at midnight |
twice_monthly(1, |
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, |
The first day of January, April, July, and October at midnight, or the given day and time of those months |
yearly(), yearly_on(6, |
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:
1schedule.command("reports:generate").weekly().mondays().at("13:00");1schedule.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:
1schedule.command("emails:send").hourly().between("08:00", "17:00");1schedule.command("emails:send").hourly().between("08:00", "17:00");
Use environments to restrict a task to specific environments matching APP_ENV:
1schedule.command("emails:send")2 .daily()3 .environments(["staging", "production"]);1schedule.command("emails:send")2 .daily()3 .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 laravel::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:
1schedule2 .command("emails:send")3 .daily()4 .skip(async || {5 let today = laravel::now();67 today.month() == 12 && today.day() == 258 });1schedule2 .command("emails:send")3 .daily()4 .skip(async || {5 let today = laravel::now();67 today.month() == 12 && today.day() == 258 });
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:
1schedule2 .command("reports:send")3 .twice_daily(13, 14)4 .when(async || -> laravel::Result<bool> {5 Ok(laravel::now().in_tz("America/Chicago")?.hour() == 8)6 });1schedule2 .command("reports:send")3 .twice_daily(13, 14)4 .when(async || -> laravel::Result<bool> {5 Ok(laravel::now().in_tz("America/Chicago")?.hour() == 8)6 });
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:
1schedule.command("emails:send").every_minute().without_overlapping();1schedule.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:
1#[schedule::tasks]2fn schedule(schedule: &mut Schedule) {3 schedule.use_cache("database");45 schedule.command("emails:send").every_minute().without_overlapping();6}1#[schedule::tasks]2fn schedule(schedule: &mut Schedule) {3 schedule.use_cache("database");45 schedule.command("emails:send").every_minute().without_overlapping();6}
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:
1use laravel::time::ToSpan;23schedule4 .call(prune_recent_users)5 .name("prune-recent-users")6 .every_minute()7 .without_overlapping_for(10.minutes());1use laravel::time::ToSpan;23schedule4 .call(prune_recent_users)5 .name("prune-recent-users")6 .every_minute()7 .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:
1laravel schedule:clear-cache1laravel schedule:clear-cache
Running 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:
1schedule.command("reports:generate")2 .fridays()3 .at("17:00")4 .on_one_runner();1schedule.command("reports:generate")2 .fridays()3 .at("17:00")4 .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:
1for account in [42, 84] {2 schedule3 .call(move || async move { tracing::info!(account, "Checking account") })4 .name(format!("check-account-{account}"))5 .hourly()6 .on_one_runner();7}1for account in [42, 84] {2 schedule3 .call(move || async move { tracing::info!(account, "Checking account") })4 .name(format!("check-account-{account}"))5 .hourly()6 .on_one_runner();7}
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:
1schedule.command("reports:generate").hourly();2schedule.command("accounts:reconcile").hourly().blocking();3schedule.command("statements:send").hourly();1schedule.command("reports:generate").hourly();2schedule.command("accounts:reconcile").hourly().blocking();3schedule.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:
1schedule.command("orders:sync").every_second();1schedule.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:
1./your-app schedule:interrupt1./your-app schedule:interrupt
Each 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):
1schedule2 .command("emails:send")3 .daily()4 .send_output_to("storage/logs/emails.log");56schedule7 .command("emails:send")8 .daily()9 .append_output_to("storage/logs/emails.log");1schedule2 .command("emails:send")3 .daily()4 .send_output_to("storage/logs/emails.log");56schedule7 .command("emails:send")8 .daily()9 .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:
1use laravel::event::Event;2use laravel::schedule::TaskResult;34schedule5 .command("emails:send")6 .daily()7 .before(async || tracing::info!("Sending emails"))8 .on_success(async |result: Event<TaskResult>| {9 tracing::info!(duration = %result.duration, "Sent emails");10 })11 .on_failure(async |result: Event<TaskResult>| {12 tracing::error!(error = ?result.error, "Couldn't send emails");13 });1use laravel::event::Event;2use laravel::schedule::TaskResult;34schedule5 .command("emails:send")6 .daily()7 .before(async || tracing::info!("Sending emails"))8 .on_success(async |result: Event<TaskResult>| {9 tracing::info!(duration = %result.duration, "Sent emails");10 })11 .on_failure(async |result: Event<TaskResult>| {12 tracing::error!(error = ?result.error, "Couldn't send emails");13 });
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:
1use laravel::event::Event;2use laravel::schedule::TaskResult;3use laravel::storage;45schedule6 .command("reports:generate")7 .daily()8 .send_output_to("storage/logs/report.log")9 .on_success(async |result: Event<TaskResult>| -> laravel::Result<()> {10 if let Some(output) = &result.output {11 let stream = output.stream().await?;1213 storage::disk("s3")?.write_stream("logs/report.log", stream).await?;14 }1516 Ok(())17 });1use laravel::event::Event;2use laravel::schedule::TaskResult;3use laravel::storage;45schedule6 .command("reports:generate")7 .daily()8 .send_output_to("storage/logs/report.log")9 .on_success(async |result: Event<TaskResult>| -> laravel::Result<()> {10 if let Some(output) = &result.output {11 let stream = output.stream().await?;1213 storage::disk("s3")?.write_stream("logs/report.log", stream).await?;14 }1516 Ok(())17 });
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 laravel::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:
1use laravel::event::{Event, listener};2use laravel::schedule::events::ScheduledTaskFailed;34#[listener]5pub async fn log_failed_task(event: Event<ScheduledTaskFailed>) {6 tracing::error!(7 task = %event.result.task.name,8 error = ?event.result.error,9 "Scheduled task failed",10 );11}1use laravel::event::{Event, listener};2use laravel::schedule::events::ScheduledTaskFailed;34#[listener]5pub async fn log_failed_task(event: Event<ScheduledTaskFailed>) {6 tracing::error!(7 task = %event.result.task.name,8 error = ?event.result.error,9 "Scheduled task failed",10 );11}
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:
1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34impl ServiceProvider for ReportsProvider {5 fn register(&self, app: &mut Registrar) {6 app.commands().add::<GenerateReport>();78 app.schedule().command("reports:generate").daily_at("06:00");9 }10}1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34impl ServiceProvider for ReportsProvider {5 fn register(&self, app: &mut Registrar) {6 app.commands().add::<GenerateReport>();78 app.schedule().command("reports:generate").daily_at("06:00");9 }10}
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:
1// src/console/mod.rs2use laravel::db;3use laravel::schedule::{self, Schedule};45#[schedule::tasks]6fn schedule(schedule: &mut Schedule) {7 schedule.call(prune_recent_users).daily();8}910pub async fn prune_recent_users() -> laravel::Result<()> {11 db::table("recent_users").delete().await?;1213 Ok(())14}1// src/console/mod.rs2use laravel::db;3use laravel::schedule::{self, Schedule};45#[schedule::tasks]6fn schedule(schedule: &mut Schedule) {7 schedule.call(prune_recent_users).daily();8}910pub async fn prune_recent_users() -> laravel::Result<()> {11 db::table("recent_users").delete().await?;1213 Ok(())14}
Your test then calls the function directly inside #[laravel::test], which runs inside the test's application and database:
1// tests/scheduling.rs2use laravel::db;3use laravel::testing::prelude::*;45#[laravel::test]6async fn pruning_recent_users_empties_the_table(app: Application) -> laravel::Result<()> {7 db::table("recent_users")8 .insert(db::values! { name: "Taylor" })9 .await?;1011 app::console::prune_recent_users().await?;1213 app.assert_database_count("recent_users", 0).await;1415 Ok(())16}1// tests/scheduling.rs2use laravel::db;3use laravel::testing::prelude::*;45#[laravel::test]6async fn pruning_recent_users_empties_the_table(app: Application) -> laravel::Result<()> {7 db::table("recent_users")8 .insert(db::values! { name: "Taylor" })9 .await?;1011 app::console::prune_recent_users().await?;1213 app.assert_database_count("recent_users", 0).await;1415 Ok(())16}
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:
1app.command("emails:send Taylor --force").await.assert_successful();23app.job(SendWeeklyDigest).await.assert_succeeded();1app.command("emails:send Taylor --force").await.assert_successful();23app.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.