
examples.jms.scheduled-message.readme.html Maven / Gradle / Ivy
The newest version!
HornetQ Scheduled Message Example
JMS Scheduled Message Example
This example shows you how to send a scheduled message to a JMS Queue using HornetQ.
A Scheduled Message is a message that will be delivered at a time specified by the sender. To do this,
simply set a HDR_SCHEDULED_DELIVERY_TIME header property. The value of the property should be the time of
delivery in milliseconds.
In this example, a message is created with the scheduled delivery time set to 5 seconds after the current time.
Example step-by-step
To run the example, simply type ./build.sh
(or build.bat
on windows) from this directory
- First we need to get an initial context so we can look-up the JMS connection factory and destination objects from JNDI. This initial context will get it's properties from the
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
- We look-up the JMS queue object from JNDI
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
- We look-up the JMS connection factory object from JNDI
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
- We create a JMS connection
connection = cf.createConnection();
- We create a JMS session. The session is created as non transacted and will auto acknowledge messages.
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- We create a JMS message producer on the session. This will be used to send the messages.
MessageProducer producer = session.createProducer(queue);
- We create a JMS text message that we are going to send.
TextMessage message = session.createTextMessage("This is a scheduled message message which will be delivered in 5 sec.");
- We schedule the delivery time to be 5 sec later.
long time = System.currentTimeMillis();
time += 5000;
message.setLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME.toString(), time);
- We send message to the queue
messageProducer.send(message);
- We create a JMS Message Consumer to receive the message.
MessageConsumer messageConsumer = session.createConsumer(queue);
- We start the connection. In order for delivery to occur on any consumers or subscribers on a connection, the connection must be started
connection.start();
- We use a blocking receive() to consume the message and see when the message arrives.
TextMessage messageReceived = (TextMessage) messageConsumer.receive();
- And finally, always remember to close your JMS connections and resources after use, in a
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}
More information
- User Manual's Scheduled Messages chapter
© 2015 - 2025 Weber Informatics LLC | Privacy Policy