DEV Community

loading...

Use symfony/messenger without supervisor

fadymr profile image F.R Michel ・1 min read

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!

Discussion (2)

pic
Editor guide
Collapse
parijke profile image
Paul Rijke

Brilliant trick... I actually postponed using Messenger because of the worker problem on my shared hosting.

Collapse
fadymr profile image
F.R Michel Author

I had the same problem.