Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 67 ยท Queues, Events and Notifications

Task Scheduling

Run recurring jobs with the Laravel scheduler: routes/console.php, frequency helpers, withoutOverlapping, onOneServer, the single cron entry and schedule:work.

Apps have chores: delete expired tokens every night, send a weekly digest on Monday morning, refresh exchange rates every hour. The traditional answer is cron, the Unix scheduler. But managing a pile of cron lines on each server has problems. The schedule lives outside your repository, nobody reviews changes to it, it is easy to forget when you add a server, and each line has to repeat the PHP path and the project folder.

Laravel's task scheduler moves the schedule into your code. You describe the tasks in PHP, and the server needs just one cron entry that runs every minute and asks Laravel, "what is due right now?" Your schedule is then versioned, reviewed and deployed together with the app.

Laravel cannot run on this site, so Laravel code blocks are read-only. The runnable examples are plain PHP stand-ins for the scheduler's logic, and each section says which is which.

How it works

sequenceDiagram
    participant Cron as System cron (every minute)
    participant Art as php artisan schedule:run
    participant S as Schedule
    participant T as Task
    Cron->>Art: run
    Art->>S: which tasks are due now?
    S-->>Art: list of due tasks
    Art->>T: run each due task
    T-->>Art: done

Cron wakes Laravel once a minute, and Laravel decides which tasks to run.

The server's only cron line is this (adjust the path):

Terminal
* * * * * cd /var/www/my-app && php artisan schedule:run >> /dev/null 2>&1

On Laravel Cloud and Forge you enable the scheduler with a switch instead of editing cron by hand. Locally, run php artisan schedule:work, a foreground process that triggers schedule:run every minute so you do not need cron on your laptop.

Defining tasks

In current Laravel versions, schedules go in routes/console.php (older apps used app/Console/Kernel.php) with the Schedule facade:

PHP
<?php

use App\Jobs\SendWeeklyDigest;
use Illuminate\Support\Facades\Schedule;

// An Artisan command
Schedule::command('sanctum:prune-expired --hours=24')->daily();

// A queued job
Schedule::job(new SendWeeklyDigest)->weeklyOn(1, '08:00');

// A closure
Schedule::call(function () {
    DB::table('password_reset_tokens')->where('created_at', '<', now()->subDay())->delete();
})->hourly();

// A shell command
Schedule::exec('node /home/forge/script.js')->daily();

Prefer Schedule::command() and Schedule::job(). Commands and jobs are named, testable and runnable by hand with php artisan, while closures are harder to reuse. For slow work, schedule a job and let the queue do it, so the scheduler returns quickly. Writing a command is covered in Artisan and custom commands.

Frequency helpers

Instead of cryptic cron strings, use readable methods:

PHP
Schedule::command('reports:build')->everyMinute();
Schedule::command('reports:build')->everyFiveMinutes();
Schedule::command('reports:build')->everyThirtyMinutes();
Schedule::command('reports:build')->hourly();
Schedule::command('reports:build')->hourlyAt(17);              // at :17 past each hour
Schedule::command('reports:build')->daily();                   // 00:00
Schedule::command('reports:build')->dailyAt('13:30');
Schedule::command('reports:build')->twiceDaily(1, 13);
Schedule::command('reports:build')->weekdays()->at('08:00');
Schedule::command('reports:build')->weeklyOn(1, '08:00');      // 1 = Monday
Schedule::command('reports:build')->monthlyOn(4, '15:00');
Schedule::command('reports:build')->lastDayOfMonth('23:00');
Schedule::command('reports:build')->quarterly();
Schedule::command('reports:build')->cron('15 3 * * 1-5');      // raw cron

A cron expression has five fields: minute, hour, day of month, month and day of week. */5 means "every fifth", 1-5 is a range and 1,15 is a list. Most of the time the helpers are clearer, but cron() covers anything unusual.

Times use the app's timezone (config('app.timezone'), which is UTC by default). To schedule in a different zone, chain ->timezone('America/New_York'). Be careful about daylight saving time, which can skip or repeat an hour: avoid scheduling important work at times that do not exist on some days.

Conditions and constraints

PHP
Schedule::command('emails:send')
    ->weekdays()
    ->between('8:00', '17:00')
    ->when(fn () => Feature::active('digest'))
    ->skip(fn () => app()->isDownForMaintenance())
    ->environments(['production']);

when() runs the task only if the closure returns true, skip() does the opposite, between() limits the time of day and environments() restricts it by environment. Scheduled tasks do not run while the app is in maintenance mode unless you add ->evenInMaintenanceMode().

Overlap, background runs and multiple servers

By default, schedule:run starts a task and waits for it to finish before starting the next due one. Two problems follow.

Overlap. If a task scheduled every minute takes three minutes, copies of it pile up and fight over the same data. Add withoutOverlapping(): Laravel takes a lock, and while the previous run holds it, the next run is skipped. If a process crashes, the lock could stay forever, so the lock has a time limit (24 hours by default) that you can shorten, for example withoutOverlapping(10) for ten minutes.

Blocking. One slow task delays the others in the same minute. runInBackground() starts a task in a separate process, so it does not hold up the rest.

Multiple servers. If your app runs on three web servers, each has the cron line, so each runs every task. A task that must run once per tick needs onOneServer():

PHP
Schedule::command('invoices:send')
    ->dailyAt('06:00')
    ->onOneServer()
    ->withoutOverlapping();

onOneServer() uses a lock in the cache, so all servers must share one cache store such as Redis or the database; a per-server file cache cannot coordinate. A common alternative is to run the scheduler on a single dedicated machine.

Output, hooks and monitoring

PHP
Schedule::command('backup:run')
    ->daily()
    ->appendOutputTo(storage_path('logs/backup.log'))
    ->emailOutputOnFailure('[email protected]')
    ->before(fn () => Log::info('backup starting'))
    ->onSuccess(fn () => Log::info('backup ok'))
    ->onFailure(fn () => Log::error('backup failed'))
    ->pingOnSuccess('https://hc.example.com/ping/abc123');

The last line illustrates a "dead man's switch": a monitoring service expects a ping and alerts you when it does not arrive. A scheduler that silently stopped is a classic production surprise, so monitor the success of important tasks and not only their failure.

Useful commands:

Terminal
php artisan schedule:list              # all tasks with their next due time
php artisan schedule:run               # what cron calls
php artisan schedule:work              # local development loop
php artisan schedule:test              # pick one task and run it now

A scheduler that decides what is due

The core of the scheduler is a function: given the current minute, which tasks match? This stand-in implements a tiny five-field cron matcher and a schedule of tasks, using a fixed list of times so the output is the same every run.

PHP A scheduler that finds due tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the Monday 08:00 line: five tasks are due, because everyMinute, everyFifteen (minute 0), dailyAt08, weekdaysAt08 and mondayDigest all match. On Saturday, the weekday and Monday tasks are not due. Laravel's real implementation uses a well-tested cron library for the same job, including the day-of-week names and edge cases this stand-in leaves out.

The overlap lock

withoutOverlapping() is a lock with an expiry. Here is the logic as an in-memory model, with time measured in minutes:

PHP withoutOverlapping with an expiring lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With a three-minute task, the lock keeps minutes 1 and 2 from starting copies. The expiry matters too: if the process died without releasing, the lock would clear itself after ten minutes instead of blocking the task forever.

Testing and good habits

  • Test the command or job itself with a normal test; the scheduler only decides when to call it.
  • Keep tasks idempotent: a missed minute or a duplicate run should do no harm.
  • Dispatch long work as a queued job so the scheduler tick finishes quickly.
  • Log and monitor. See deploying Laravel for running workers and the scheduler in production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many cron entries does a Laravel server need for the scheduler?

    Cron calls schedule:run every minute, and Laravel decides from your code which tasks are due. The schedule is defined in routes/console.php.
  2. 2. A task scheduled every minute takes three minutes and corrupts data when copies overlap. What do you add?

    withoutOverlapping() takes a lock, so a new run is skipped while the previous one still holds it. The lock expires after a time limit to avoid being stuck forever.
  3. 3. Your app runs on three servers that each have the cron entry. How do you run a task only once per tick?

    onOneServer() uses a lock in the cache, so the servers must share one cache store. Otherwise each server acquires its own lock and runs the task.
  4. 4. What does php artisan schedule:work do?

    schedule:work is a long-running local alternative to the cron entry, and schedule:list shows the tasks and their next run times.

Summary

  • The scheduler keeps your schedule in code (routes/console.php); the server needs one cron entry running schedule:run every minute.
  • Prefer Schedule::command() and Schedule::job(); use frequency helpers like dailyAt() and weeklyOn(), or cron() for anything unusual.
  • withoutOverlapping() prevents overlapping runs, runInBackground() avoids blocking, and onOneServer() needs a shared cache.
  • Add hooks, output logging and ping monitoring to notice when scheduled work stops.
  • Keep tasks idempotent and push heavy work to queues.

Next: Real-Time Features with Broadcasting and Reverb