Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 62 ยท Events, Messaging and Console

Scheduler, Lock and Cron Jobs

Run recurring work in Symfony with the Scheduler component and RecurringMessage, prevent overlapping runs with the Lock component, and compare it with plain cron.

Applications have chores that nobody triggers by clicking: delete expired password-reset tokens every hour, email a digest at 08:00, build a report every Monday. For decades the tool for this was cron, a Unix daemon that runs a command on a schedule. Cron still works well, but it lives outside your code, it is easy to forget when you deploy to a new server, and it knows nothing about your application.

Symfony offers two components that make recurring work part of the project. Scheduler describes what runs when in PHP, and sends each occurrence as a Messenger message. Lock makes sure that only one process does a job at a time, which matters as soon as two workers, two servers or two overlapping cron runs could start the same job. All real Symfony code here is read-only; two runnable stand-ins show the ideas: a cron-expression schedule and a lock with a time-to-live.

Option 1: plain cron plus a console command

The simplest approach needs no extra component: write a console command and call it from the server's crontab.

Terminal
# crontab -e (real server setup, read-only)
# minute hour day-of-month month day-of-week  command
0 3 * * *  cd /var/www/app && php bin/console app:cleanup-tokens --env=prod >> /var/log/cleanup.log 2>&1

The five fields are minute, hour, day of month, month and day of week. * means "every", */15 means "every 15", 1-5 is a range and 1,15 a list. So 0 3 * * * is "at 03:00 every day" and 30 9 * * 1 is "09:30 every Monday".

Cron's weaknesses are practical rather than technical. The schedule is not in version control unless you work for it, every server needs the same crontab, and if a run takes longer than the interval, two copies run at once. The Lock component fixes that last problem, and Scheduler fixes the others.

Option 2: the Scheduler component

Install it with composer require symfony/scheduler. A schedule is a class that returns a Schedule full of RecurringMessage objects. Each occurrence dispatches a plain message, and an ordinary message handler does the work.

PHP
// src/Scheduler/MainSchedule.php (real Symfony, read-only)
namespace App\Scheduler;

use App\Message\CleanupExpiredTokens;
use App\Message\SendDailyDigest;
use Symfony\Component\Scheduler\Attribute\AsSchedule;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\ScheduleProviderInterface;

#[AsSchedule]
final class MainSchedule implements ScheduleProviderInterface
{
    public function getSchedule(): Schedule
    {
        return (new Schedule())->add(
            RecurringMessage::every('1 hour', new CleanupExpiredTokens()),
            RecurringMessage::cron('0 8 * * *', new SendDailyDigest()),
        );
    }
}
PHP
// src/MessageHandler/CleanupExpiredTokensHandler.php (real Symfony, read-only)
#[AsMessageHandler]
final class CleanupExpiredTokensHandler
{
    public function __invoke(CleanupExpiredTokens $message): void
    {
        // delete rows older than 24 hours
    }
}

RecurringMessage::every() takes an interval ('10 seconds', '1 hour', '1 day'), and cron() takes a cron expression and an optional time zone; both accept further options such as a start and end time. Cron expressions in cron() also support hashed forms (#midnight, #daily) that spread jobs across the day so many tasks do not all start on the same minute.

#[AsSchedule] gives the schedule the name default (pass a name to the attribute for others). Symfony creates a matching Messenger transport called scheduler_default, and you run the schedule with a worker:

Terminal
# real Symfony, read-only
php bin/console messenger:consume scheduler_default -vv
php bin/console debug:scheduler

debug:scheduler lists each recurring message with its next run times, which is the quickest way to check that a cron expression says what you meant.

flowchart LR
    S["Schedule<br/>(RecurringMessage list)"] --> T["scheduler_default<br/>transport"]
    T --> W["Worker<br/>messenger:consume scheduler_default"]
    W --> H["Message handler<br/>does the work"]

The scheduler transport emits a message whenever a recurring message is due; a worker reads it and calls the normal handler.

Two shortcuts exist for the common cases: #[AsCronTask('0 3 * * *')] and #[AsPeriodicTask('1 hour')] can be placed on a console command or on a service method, and Symfony adds them to the default schedule for you. Use the explicit Schedule class when you want everything visible in one file.

Things to know before relying on it

  • A worker must be running. Scheduler is not magic: nothing runs unless messenger:consume scheduler_default is alive, so keep it under Supervisor or systemd like any worker, and restart it after deploys.
  • Run one per schedule, or add a lock. If several servers each run a scheduler worker, each would dispatch every occurrence. Give the schedule a lock with ->lock($lockFactory->createLock('scheduler-default')) so that only one instance emits messages.
  • Missed runs. By default a worker only looks forward from when it started. Add ->stateful($cachePool) to the schedule and Scheduler remembers the last run, so after downtime it catches up the occurrences it missed.
  • Slow jobs. A long task blocks the worker that handles it. Dispatch the real work to another transport (a handler can simply dispatch a second message) so the schedule stays responsive.
  • Use UTC thinking. Daily jobs in a time zone with daylight saving time can run twice or skip an hour; use UTC unless the local time matters, and set the time zone explicitly when it does.

How a schedule decides: a stand-in you can run

The stand-in below implements the part of cron that matters: matching a five-field expression against a moment in time. It then scans a fixed 24-hour window (Monday, 5 January 2026, UTC) to show when each recurring message would fire. It does not read the system clock, so the output is the same every time.

PHP Cron expressions and a schedule (stand-in)

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.

On Monday all four messages fire (the digest at 08:00, the weekly report at 09:30, the token cleanup at 03:00 and the ping 96 times). On Saturday the day-of-week fields 1-5 and 1 no longer match, so the digest and weekly report are silent while the daily and every-15-minutes jobs continue. One simplification: real cron has a special rule when both the day-of-month and day-of-week fields are restricted (a match on either is enough); this stand-in requires both.

The Lock component

A lock is a named flag that only one holder can own at a time. Any process that wants to do guarded work first tries to take the lock and, if it is taken, skips the work or waits. Install it with composer require symfony/lock.

PHP
// src/Service/ReportRunner.php (real Symfony, read-only)
use Symfony\Component\Lock\LockFactory;

final class ReportRunner
{
    public function __construct(private LockFactory $lockFactory)
    {
    }

    public function run(): void
    {
        $lock = $this->lockFactory->createLock('nightly-report', ttl: 300);

        if (!$lock->acquire()) {
            return; // another process is already building the report
        }

        try {
            // ... long running work, call $lock->refresh() in long loops ...
        } finally {
            $lock->release();
        }
    }
}

Facts about locks worth remembering:

  • acquire() does not wait by default; it returns false at once if the lock is held. acquire(true) blocks until it gets the lock.
  • The TTL (time to live) is the safety net. If a process crashes while holding the lock, the lock expires after ttl seconds instead of blocking everybody forever. Long jobs call refresh() to push the expiry forward.
  • Where the lock lives decides what it protects. The default flock store uses files on one machine, so it protects processes on that server only. For several servers use a shared store such as Redis, a database (doctrine://default) or Memcached.
YAML
# config/packages/lock.yaml (real Symfony, read-only)
framework:
    lock: '%env(LOCK_DSN)%'   # for example flock, redis://localhost, doctrine://default

You can name several lock configurations and autowire them by argument name. Console commands have a shortcut, the LockableTrait: calling $this->lock() at the start of execute() returns false if the same command is already running, and $this->release() frees it. That alone cures the overlapping-cron problem from the first section.

sequenceDiagram
    participant A as Worker A
    participant L as Lock store
    participant B as Worker B
    A->>L: acquire("nightly-report", ttl 30)
    L-->>A: true
    B->>L: acquire("nightly-report")
    L-->>B: false (held by A)
    Note over A: A crashes, never releases
    B->>L: acquire after the TTL has passed
    L-->>B: true

A lock with a TTL: B is refused while A holds it, and takes over after A's lock expires.

A lock you can run

This stand-in keeps a tiny lock store with a logical clock (whole seconds, no real time), so every run gives the same result. It shows refusal while a lock is held, recovery after a crash through the TTL, and release.

PHP A lock store with a time to live (stand-in)

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.

Read the timeline line by line: B is refused while A works; A's refresh at t=20 extends its lock until t=50, so B is still refused at t=40; after A crashes, nothing releases the lock, but the TTL does, so B gets it at t=51; and A is refused until B releases. Without the TTL, the crash at t=40 would have blocked the job forever.

Putting them together

A production-ready recurring job usually combines the pieces: a RecurringMessage in the schedule says when, a Messenger handler does the work, and a lock inside the handler (or on the schedule itself) says only one at a time. If you stay with cron, the crontab line says when, a console command does the work and LockableTrait prevents overlaps. Either way, make the job idempotent: if it runs twice or is retried, the result is the same as running once.

You now have the whole toolbox for work outside the request cycle: events for reactions, Messenger for background tasks, console commands for operations, Mailer and Notifier for talking to people, and Scheduler and Lock for repetition. The next lessons use these ideas to build and serve JSON APIs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the cron expression 30 9 * * 1 mean?

    The fields are minute (30), hour (9), day of month (), month () and day of week (1, Monday).
  2. 2. What must be running for a Symfony Scheduler schedule to actually fire?

    Scheduler emits messages through a Messenger transport. Without a worker consuming it, nothing happens.
  3. 3. Why does a lock have a TTL?

    If the holder dies without releasing, the lock expires after the TTL and another process can continue.
  4. 4. Your app runs on three servers. Which lock store protects a job across all of them?

    flock uses files on one machine. A shared store is needed so that all servers see the same lock.
  5. 5. A cron job sometimes runs longer than its interval and two copies overlap. What is the simplest fix?

    A lock lets the second copy notice that the first is still running and exit instead of doing the work twice.

Summary

  • Cron plus a console command is the simplest way to run recurring jobs; its schedule lives on the server and overlapping runs are your problem.
  • The Scheduler component describes recurring work in PHP with RecurringMessage::every() and cron(), dispatches it as Messenger messages and needs a worker on scheduler_default; debug:scheduler shows the next runs.
  • For several servers, give the schedule a lock; add stateful() to catch up on missed runs.
  • The Lock component gives you named locks with a TTL: acquire(), refresh(), release(); choose a shared store (Redis, database) when more than one machine is involved.
  • Make recurring jobs idempotent, and use LockableTrait to stop overlapping command runs.

Next up: Building JSON APIs.