0

I'm trying to test my process of handling some data via messenger in Symfony.

I try the following:

At first, I define my worker.

$event_dispatcher = $this->getContainer()->get(EventDispatcherInterface::class);
$logger = $this->getContainer()->get(LoggerInterface::class);
$message_bus = $this->getContainer()->get(MessageBusInterface::class);
$transport = $this->getContainer()->get("messenger.transport.async");
$worker = new Worker([$transport], $message_bus, $event_dispatcher, $logger);

Then after this, some code runs that sends a message to the messenger. I tested this code and this works fine. With dumping $transport->get() I see that my messages have been successfully sending to the worker and database.

Now at the end of my unit test, I run the worker via $worker->run(). Since the messenger only handles a couple of actions/queries it should only take a little bit for it to finish. But it looks like it is just idling there. I call $worker->stop() directly after $worker->run() but it does not reach there.

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
Jorn Barkhof
  • 264
  • 1
  • 16

1 Answers1

1

The Worker will continue to run and process the queue unless you set a limit or the worker crashes, so the behavior you are seeing is intended.

You can use the following code samples from the official ConsumeMessagesCommand in order to modify your worker:

<?php

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Messenger\EventListener\StopWorkerOnMessageLimitListener;
use Symfony\Component\Messenger\EventListener\StopWorkerOnTimeLimitListener;

$eventDispatcher->addSubscriber(
  // stop after 10 messages (but won't stop when fewer are processed)
  new StopWorkerOnMessageLimitListener(10)
);

$eventDispatcher->addSubscriber(
  // stop after 10 seconds (can take longer when the message processing exceeds the 10 seconds)
  new StopWorkerOnTimeLimitListener(10)
);

JimmyBlu
  • 648
  • 5
  • 20