July 22, 2019

Scheduled Message Consumer on ActiveMQ with Spring DMLC and Quartz

In this post I show how to schedule a task to start and stop a JMS MessageListener (Consumer) on ActiveMQ on a predefine date and time with Quartz Scheduler and Spring DefaultMessageListenerContainer (DMLC). From the other side (Producer) if you want to see how the delay and schedule message delivery works, I suggest the ActiveMQ scheduler built-in.


ActiveMQ 5.11.1
JDK 1.8
Maven 3.2
Spring 3.0.5.RELEASE
Quartz Scheduler 1.5.2

SOURCE CODE (/giuseu/activemq)

git clone https://gitlab.com/giuseppeurso-eu/activemq



This is the MessageListener implementation. The onMessage() method is responsible for the consumption of messages. I create two methods startConsumption() and stopConsumption() to run start/stop on the DMLC Spring object. The instance of DMLC will be defined later via dependency-injection in the beans XML file.



A simple class which make use of Spring JmsTemplate to publish a number of messages. Destinations[ ] could be useful in case of sending on multiple queues.


Spring XML configuration

Here is the Spring beans definition.Pay attention to the autoStartup property which is false in the sampleDMLC bean. I will use the Quartz Scheduer to define two jobs which will be responsible for starting and stopping of the message consumer. In order to define the job details I use MethodInvokingJobDetailFactoryBean and SchedulerFactoryBean. The two jobs have a different targetMethod to start/stop message consumption but the same targetObject which refers to the same consumer. The consumer bean includes a property sampleListener injected via Spring which creates an instance of DMLC.

In this example, I use a simple cron expression to start message consumption in a given time and stop it after 15 seconds.


Run Test

Finally a simple JUnit test class ScheduledConsumerTest, to simulate a use case. This class sends a message on a sample queue and waits until 20 seconds with a Thread.sleep for the job executions.




Related posts


    1. Giuseppe

      The Quartz scheduler performs asynchronous actions and knows nothing of what happens while the messages are consumed. If you need to do something when consumption is finished, you should make programmatically in the Consumer class.
      Otherwise you can play with the cronExpression attribute which is responsible for starting and stopping of the message consuming:


Leave a Reply

Your email address will not be published.