publicstaticvoidmain(String[] args)throws Exception { // Instantiate a producer to send scheduled messages DefaultMQProducerproducer=newDefaultMQProducer("ExampleProducerGroup"); // Launch producer producer.start(); inttotalMessagesToSend=100; for (inti=0; i < totalMessagesToSend; i++) { Messagemessage=newMessage("TestTopic", ("Hello scheduled message " + i).getBytes()); // This message will be delivered to consumer 10 seconds later. message.setDelayTimeLevel(3); // Send the message producer.send(message); }
// Shutdown producer after use. producer.shutdown(); }
}
3 Verification
You should see messages are consumed about 10 seconds later than their storing time.
4 Use scenarios for scheduled messages
For example, in e-commerce, if an order is submitted, a delay message can be sent, and the status of the order can be checked after 1 hour. If the order is still unpaid, the order can be cancelled and the inventory released.
Nowadays RocketMq does not support any time delay. It needs to set several fixed delay levels, which correspond to level 1 to 18 from 1s to 2h. Message consumption failure will enter the delay message queue. Message sending time is related to the set delay level and the number of retries.