Back to symfony.com

Demo 3 of 10 · 2 min

Click any paragraph or press to highlight its code

Recurring tasks with Scheduler

Forget editing crontabs on your servers. One attribute turns any invokable service into a recurring task, versioned with the rest of your code and using human-readable frequencies (cron expressions work too).

The task is a normal service: it can autowire repositories, the mailer or anything else. Being plain PHP, you can unit test it like any other class.

Tasks run through Messenger, so they reuse the same workers, error handling and retries. On top of this, Symfony provides jitter, locks to avoid overlapping runs, and a command to debug the schedule.

<?phpnamespace App\Scheduler;use App\Repository\InvoiceRepository;use Symfony\Component\Scheduler\Attribute\AsPeriodicTask;#[AsPeriodicTask(frequency: '1 day', from: '09:00')]class SendInvoiceReminders{    public function __construct(        private InvoiceRepository $invoices,    ) {    }    public function __invoke(): void    {        foreach ($this->invoices->findOverdue() as $invoice) {            // ... send the reminder        }    }}
$ php bin/console messenger:consume scheduler_default$ php bin/console debug:scheduler