有時候咱們不但願消息立刻被broker投遞出去,而是想要消息60秒之後發給消費者,或者咱們想讓消息沒隔必定時間投遞一次,一共投遞指定的次數。。。apache
相似這種需求,ActiveMQ提供了一種broker端消息定時調度機制。session
咱們只須要把幾個描述消息定時調度方式的參數做爲屬性添加到消息,broker端的調度器就會按照咱們想要的行爲去處理消息。spa
一共有四個屬性:code
Property name | type | description |
---|---|---|
AMQ_SCHEDULED_DELAY | long | 延遲投遞的時間 |
AMQ_SCHEDULED_PERIOD | long | 重複投遞的時間間隔 |
AMQ_SCHEDULED_REPEAT | int | 重複投遞次數 |
AMQ_SCHEDULED_CRON | String | Cron表達式 |
固然ActiveMQ也提供了一個封裝的消息類型:org.apache.activemq.ScheduledMessage.ip
使用示例,延遲60秒:get
MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage("test msg"); long time = 60 * 1000; message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); producer.send(message);
延遲30秒,投遞10次,間隔10秒:io
MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage("test msg"); long delay = 30 * 1000; long period = 10 * 1000; int repeat = 9; message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay); message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period); message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat); producer.send(message);
使用 CRON 表達式的例子:table
MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage("test msg"); message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "0 * * * *"); producer.send(message);
CRON表達式的優先級高於另外三個參數,若是在設置了CRON的同時,也有repeat和period參數,則會在每次CRON執行的時候,重複投遞repeat次,每次間隔爲period。就是說設置是疊加的效果。例如每小時都會發生消息被投遞10次,延遲1秒開始,每次間隔1秒:test
MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage("test msg"); message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "0 * * * *"); message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 1000); message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1000); message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 9); producer.send(message);