Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 30 ยท Events, Flows and Background Work

Scheduled Tasks and the Message Queue

Run recurring and background work in Shopware 6: ScheduledTask classes, handlers, Messenger messages, workers, retries and idempotent jobs, with PHP stand-ins.

Some work must not happen while a customer waits: exporting orders every night, cleaning old rows, calling a slow ERP, sending a hundred emails. Shopware 6 gives plugin developers two building blocks for this. A scheduled task says "run this every N seconds". The message queue says "do this later, in another process". Both are built on Symfony Messenger, so a scheduled task is really just a message that Shopware dispatches for you on a timer.

In this lesson you will see how a task class and its handler fit together, how the scheduler decides what is due, how workers consume messages, and how to write jobs that survive retries. The real Shopware code is read-only here, because Shopware cannot run on this site. The runnable examples are plain PHP stand-ins that copy the mechanism, and each one says what is real and what is simplified. If Messenger is new to you, read Messenger: Messages and Handlers first; for the events that often trigger such work, see Subscribers and Core Events.

Two classes make a scheduled task

A scheduled task needs a task class that names the job and its default interval, and a handler that does the work. The task class (read-only):

PHP
namespace Acme\OrderExport\ScheduledTask;

use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTask;

class ExportOrdersTask extends ScheduledTask
{
    public static function getTaskName(): string
    {
        return 'acme.order_export';
    }

    public static function getDefaultInterval(): int
    {
        return 3600; // seconds
    }
}

The name should start with your vendor prefix, because task names are global across all installed plugins. The interval is in seconds. Administrators can change the interval of a registered task later; the value in code is only the default.

The handler extends ScheduledTaskHandler and implements run() (read-only):

PHP
namespace Acme\OrderExport\ScheduledTask;

use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskHandler;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(handles: ExportOrdersTask::class)]
class ExportOrdersTaskHandler extends ScheduledTaskHandler
{
    public function __construct(
        EntityRepository $scheduledTaskRepository,
        LoggerInterface $exceptionLogger,
        private readonly OrderExporter $exporter,
    ) {
        parent::__construct($scheduledTaskRepository, $exceptionLogger);
    }

    public function run(): void
    {
        $this->exporter->exportNewOrders();
    }
}

The constructor of the parent class has changed between Shopware versions, so copy the signature from the core version you target instead of from memory. The service definitions go into services.xml (see Services and the Dependency Injection Container). The task class is a service with the tag shopware.scheduled.task, and the handler is a service with the tag messenger.message_handler when you do not use the attribute:

XML
<service id="Acme\OrderExport\ScheduledTask\ExportOrdersTask">
    <tag name="shopware.scheduled.task"/>
</service>

<service id="Acme\OrderExport\ScheduledTask\ExportOrdersTaskHandler">
    <argument type="service" id="scheduled_task.repository"/>
    <argument type="service" id="logger"/>
    <argument type="service" id="Acme\OrderExport\OrderExporter"/>
    <tag name="messenger.message_handler"/>
</service>

Tasks are stored in the scheduled_task table. A new task row is created when the plugin is installed or activated (see Plugin Structure and Lifecycle); during development you can force registration with bin/console scheduled-task:register.

How a task actually runs

The table row holds the task name, the run interval, a status and the next execution time. Statuses include scheduled, queued, running, failed and inactive. Two separate processes move a row through them:

  1. The scheduler (bin/console scheduled-task:run) looks for rows that are scheduled and due, sets them to queued and dispatches the task class as a message. Without --no-wait it keeps looping; with --no-wait it checks once and exits, which suits a system cron entry.
  2. A worker (bin/console messenger:consume async) takes the message from the transport, calls your handler, and the base handler sets the row to running, then back to scheduled with a new next execution time when run() returns.
flowchart LR
    A["scheduled_task row<br/>(status: scheduled)"] -->|"due: scheduled-task:run"| B["queued<br/>message on transport"]
    B -->|"worker consumes"| C["handler run()"]
    C -->|"returns"| D["scheduled<br/>next run = now + interval"]
    C -->|"throws"| E["failed<br/>logged"]

The scheduler only queues work; a separate worker runs it. Without a worker, tasks stay queued forever.

That last point explains the most common bug report: "my task never runs". Either nobody runs scheduled-task:run, or nobody consumes the queue. Both processes must exist in production. A task that throws ends up in the failed state and the error is logged; check your version's behavior for failed rows before you rely on automatic recovery.

For testing, bin/console scheduled-task:run-single acme.order_export runs one task by name without waiting for its interval (check --help on your version for the exact argument).

A scheduler stand-in

This first stand-in models the scheduled_task table and the two roles. It is real in its idea (status columns, interval, queue then work) and simplified in everything else: time is a plain integer you control, so the output is always the same, and a failed task simply stays failed.

PHP A tiny scheduled_task table and scheduler

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.

Try changing the interval of acme.cleanup, or remove the workOnce() loop: the rows then stay queued forever, just like a real shop without a worker.

Messages and handlers for your own jobs

Scheduled tasks are only one use of the queue. You can dispatch any message class yourself, for example "export order X" or "sync product Y". A message is a plain object with the data the handler needs (read-only):

PHP
namespace Acme\ErpSync\Message;

use Shopware\Core\Framework\MessageQueue\AsyncMessageInterface;

class SyncProductMessage implements AsyncMessageInterface
{
    public function __construct(public readonly string $productId)
    {
    }
}

Implementing AsyncMessageInterface tells Shopware to route the message to the async transport. Dispatch it through the Symfony message bus, and handle it in a service marked as a message handler (read-only):

PHP
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\MessageBusInterface;

// in a subscriber or service:
$this->bus->dispatch(new SyncProductMessage($productId));

#[AsMessageHandler]
class SyncProductHandler
{
    public function __invoke(SyncProductMessage $message): void
    {
        // load the product by id, push it to the ERP
    }
}

Two rules keep messages healthy. First, put ids in the message, not entities. A message is serialized and may be consumed minutes later, so the handler must load fresh data. Second, keep messages small: the transport stores them in a database table or a broker, and large payloads slow everything down.

Workers: admin worker versus CLI worker

Someone must run messenger:consume. Shopware offers two ways:

  • The admin worker is JavaScript in the Administration. While an administrator has the admin open in a browser, it polls an endpoint that consumes messages. That works on a small development shop, but it stops when the browser tab closes.
  • A CLI worker is a long-running bin/console messenger:consume async low_priority --time-limit=... process kept alive by systemd or Supervisor. This is the production choice. Recent versions let you turn the admin worker off in the configuration so the two do not compete.

Long-running workers keep PHP and the container in memory, so use --time-limit or --memory-limit and let the process manager restart them. After you deploy new code, restart the workers (messenger:stop-workers), otherwise they keep running the old code. More on this in Security and Performance.

Retries, failures and idempotent jobs

Messenger retries a message that throws, with growing delays, and finally moves it to a failure transport if you configured one. That is the safety net, and it has a consequence: your handler can run more than once for the same message, and a worker that crashes mid-job can repeat it too. A job is idempotent when running it twice gives the same final state as running it once. The general idea is explained in Idempotency.

Typical ways to get there:

  • Use an "already done" marker, such as a column exported_at or a row in a log table, and check it before the side effect.
  • Prefer "set to X" over "add X": stock = 12 repeats safely, stock = stock - 1 does not.
  • Call external APIs with an idempotency key built from stable data, such as the order id.

The second stand-in shows a queue with retries, a duplicate message, a handler that fails twice before succeeding, and a handler that never succeeds and lands in a failed list. It is simplified (an array instead of a transport, no delays), but the delivery rules are the same ones you must design for.

PHP Queue with retries and an idempotent handler

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.

Notice that the duplicate mail message does no harm, the ERP handler succeeds on the third attempt, and the permanently broken job is not lost: it waits in the failed list where a human can inspect it. A failure caused by bad data (like an unknown country code) will never succeed by retrying, so in a real handler you would log it and finish normally, or throw an unrecoverable exception that skips the retries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a scheduled task class like ExportOrdersTask contain?

    The task class only names the job and gives its default interval. The work itself lives in the handler's run() method.
  2. 2. A task is stuck in the queued status and never runs. What is the most likely cause?

    The scheduler only moves due tasks to queued and dispatches a message. A worker (CLI or admin) must consume that message for the handler to run.
  3. 3. Why should a message contain a product id instead of the product entity?

    Messages are serialized and consumed later, possibly after the data changed. A small id keeps the message light and lets the handler read the current state.
  4. 4. Which handler design is safe when a message is delivered twice?

    Setting a value is idempotent, so a repeat gives the same result. Relative changes and unmarked side effects repeat on every delivery.
  5. 5. How should workers be run in production?

    Long-running CLI workers kept alive by systemd or Supervisor are the reliable choice. Restart them after deployments so they load the new code.

Summary

  • A scheduled task is a task class (name and default interval) plus a handler with a run() method; both are registered as services with the right tags.
  • The scheduled_task table tracks status and next execution time; scheduled-task:run queues due tasks and a worker runs them.
  • Your own jobs are messages, ideally implementing AsyncMessageInterface, with ids instead of entities as payload.
  • Production needs a scheduler process and CLI workers; the admin worker is a convenience for small setups.
  • Handlers can run more than once, so design them to be idempotent and put hopeless failures where a human can see them.

Next, expose your data to headless front ends in Custom Store API Routes.