activeMQ中消息的定时发送

activeMQ在5.4以后的版本中引入了定是持久化功能。用户可以通过定义下面这些的消息属性来实现定时功能:[list]
[*]AMQ_SCHEDULED_DELAY long 发送延迟
[*]AMQ_SCHEDULED_PERIOD long 发送间隔
[*]AMQ_SCHEDULED_REPEAT int 发送次数
[*]AMQ_SCHEDULED_CRON String 发送频率
[/list]
同时,activeMQ为了方便用户的使用,提供了[b]org.apache.activemq.ScheduledMessage.[/b]接口来包装了这些属性,下面就来看看这些属性的具体使用。
1.延迟60s发送

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);

2.在经过30s的延迟后,每隔10s发送一次,一共发送10次

MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("test msg");
long delay = 30 * 1000;
long period = 10 * 1000;
int repeat = 10;
message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
producer.send(message);

3.定义每小时发送一次,可以利用CRON值来设定:

MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("test msg");
message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "0 * * * *");
producer.send(message);

这里对CRON简单介绍下:
[table]

||Entry || Description || Equivalent To
||@yearly|| Run once a year|| 0 0 1 1 *
||@annually|| (same as @yearly)|| 0 0 1 1 *
||@monthly|| Run once a month|| 0 0 1 * *
||@weekly|| Run once a week|| 0 0 * * 0
||@daily|| Run once a day|| 0 0 * * *
||@midnight || (same as @daily)|| 0 0 * * *
||@hourly|| Run once an hour|| 0 * * * *
[/table]


CRON的优先级是高于发送延迟属性的。如果定义了发送次数和发送间隔的两个属性的话,那么定时器就会在CRON触发消息发送的时候,按照发送次数和发送间隔属性的配置来执行。以一个例子来解释上述声明。假设一个消息要被发送10次,每次间隔1秒钟,这样的情况每个小时要发生一次。那么我们就可以这么做:

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)


作者原创,转载请说明!
展开阅读全文

没有更多推荐了,返回首页