sajad torkamani

In a nutshell

The Symfony scheduler component helps you schedule tasks within your PHP application such as running a command every night at 2am, every hour, or at any interval your app needs.

Quick start

Install:

composer require symfony/scheduler

Create a message to represent your task:

<?php

namespace App\Message;

final class SayHello
{
    /*
     * Add whatever properties and methods you need
     * to hold the data for this message class.
     */

    // public function __construct(
    //     public readonly string $name,
    // ) {
    // }
}

Write handler:

<?php

namespace App\MessageHandler;

use App\Message\SayHello;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final class SayHelloHandler
{
    public function __construct(private LoggerInterface $logger) {}

    public function __invoke(SayHello $message): void
    {
        $this->logger->warning('Hello');
    }
}

Create schedule:

<?php

namespace App;

use App\Message\SayHello;
use Symfony\Component\Scheduler\Attribute\AsSchedule;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\ScheduleProviderInterface;
use Symfony\Contracts\Cache\CacheInterface;

#[AsSchedule]
class MainSchedule implements ScheduleProviderInterface
{
    public function __construct(
        private CacheInterface $cache,
    ) {
    }

    public function getSchedule(): Schedule
    {
        return new Schedule()
            ->add(RecurringMessage::every('3 seconds', new SayHello()))
            ->stateful($this->cache);
    }
}

The AsSchedule attribute above will create a scheduler_default transport which uses SchedulerTransport. SchedulerTransport will take care of sending your messages on the configured frequencies (every hour, once a day, etc).

The ->stateful($this->cache) bit configures your scheduler so that it retains the state of the schedule even if messenger workers are started. You’ll usually want this but read this bit if you want to learn more about that bit of code.

Consume messages:

bin/console messenger:consume -v scheduler_default

You should now say Hello printed to the console every 3 seconds.

Debug scheduler

Run bin/console debug:scheduler to see a list of your schedules that looks something like this:

Debug Symfony scheduler

Links