Use symfony/messenger without supervisor

fadymr

F.R Michel

Posted on November 16, 2020

Use symfony/messenger without supervisor

Symfony messenger use Supervisor to keep workers running but not all web hosting have a supervisor.

By default, the command will run forever and handle 10 messages before exiting with memory limit(128M) :

bin/console messenger:consume async --limit=10 --memory-limit=128M
Enter fullscreen mode Exit fullscreen mode

To work around this problem, we will use cronjobs but we don't let workers run forever.
For that we will listen on the event WorkerRunningEvent :

<?php


namespace App\Event;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerRunningEvent;

/**
 * Class ExtractFailedEvent
 * @package App\Event
 */
class CronRunningEvent implements EventSubscriberInterface
{
    public function onWorkerRunning(WorkerRunningEvent $event): void
    {
        if ($event->isWorkerIdle()) {
            $event->getWorker()->stop();
        }
    }

    /**
     * @return array<string>
     */
    public static function getSubscribedEvents()
    {
        return [
            WorkerRunningEvent::class => 'onWorkerRunning',
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

Method isWorkerIdle() return true when no message has been received by the worker.
If no message has been received , we stop the worker

To finish, set up a cron job to run evry minute

* * * * * bin/console messenger:consume async --memory-limit=128M
Enter fullscreen mode Exit fullscreen mode

Simple and easy!

💖 💪 🙅 🚩
fadymr
F.R Michel

Posted on November 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related