Apache Camel - 17 - Timer组件

Apache Camel Timer定时器组件

我将整理好的代码,上传了,有兴趣的同学可以下载下来跑跑看....

Apache Camel Timer组件 代码Demo

Apache Camel相关代码已经上传GitHub,需要的自取:GitHub - Apache Camel 完整Demo

如果觉得还行,麻烦点个Star

 

Timer Component定时器组件

The timer: component is used to generate message exchanges when a timer fires You can only consume events from this endpoint.

timer:组件用于在定时器触发时生成消息交换。您只能使用此端点的事件。

URI format URI格式

timer:name[?options]

Where name is the name of the Timer object, which is created and shared across endpoints. 

So if you use the same name for all your timer endpoints, only one Timer object and thread will be used.

其中,name是定时器对象的名称,它是通过端点创建和共享的。 

所以,如果你为所有的定时器端点使用相同的名字,将只使用一个Timer对象和线程。

You can append query options to the URI in the following format,?option=value&option=value&...

您可以按照以下格式将查询选项追加到URI中:?option=value&option=value&...

Note: The IN body of the generated exchange is null. So exchange.getIn().getBody() returns null.

注意:生成的交换的in body为空。 所以exchange.getIn().getBody()返回null。

Advanced Scheduler

See also the Quartz component that supports much more advanced scheduling.

高级调度程序

另请参阅支持更多高级调度的Quartz组件。

 

Options选项

Option

Default Value

Description

time

null

A java.util.Date the first event should be generated. If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss or yyyy-MM-dd'T'HH:mm:ss.

一个java.util.Date应该生成第一个事件。

如果使用URI,预期的模式是:yyyy-MM-dd HH:mm:ss or yyyy-MM-dd'T'HH:mm:ss.

 

pattern

null

Allows you to specify a custom Date pattern to use for setting the time option using URI syntax.

允许您指定自定义日期模式,以使用URI语法设置时间选项。

period

1000

If greater than 0, generate periodic events every period milliseconds.

如果大于0,则在每个毫秒时间内生成周期性事件。

delay

0

The number of milliseconds to wait before the first event is generated. Should not be used in conjunction with the time option.

生成第一个事件之前要等待的毫秒数。 不应该与时间选项一起使用。

fixedRate

false

Events take place at approximately regular intervals, separated by the specified period.

事件发生在大约固定的时间间隔,由指定的时间隔开。

daemon

true

Specifies whether or not the thread associated with the timer endpoint runs as a daemon.

指定与定时器端点关联的线程是否作为守护程序运行。

repeatCount

0

Camel 2.8: Specifies a maximum limit of number of fires. So if you set it to 1, the timer will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.
指定触发次数的最大限制。 所以如果你把它设置为1,定时器只会触发一次。 如果将其设置为5,则只会触发五次。 零值或负值意味着永远触发。

Exchange Properties交换属性

When the timer is fired, it adds the following information as properties to the Exchange:

计时器启动后,它将以下信息作为属性添加到Exchange中:

name

type

Description

Exchange.TIMER_NAME

String

The value of the name option.

Exchange.TIMER_TIME

Date

The value of the time option.

Exchange.TIMER_PERIOD

long

The value of the period option.

Exchange.TIMER_FIRED_TIME

Date

The time when the consumer fired.

Exchange.TIMER_COUNTER

Long

Camel 2.8: The current fire counter. Starts from 1.

Message Headers 消息头

When the timer is fired, it adds the following information as headers to the IN message

当定时器被触发时,它将以下信息作为标题添加到in message中

name

type

Description

Exchange.TIMER_FIRED_TIME

java.util.Date

The time when the consumer fired

Sample样品

To set up a route that generates an event every 60 seconds:

要设置每60秒生成一个事件的路由,请执行以下操作:

from("timer://foo?fixedRate=true&period=60000").to("bean:myBean?method=someMethodName");

Instead of 60000 you can use period=60s which is more friendly to read.

而不是60000,你可以使用周期= 60s,这是更友好的阅读。

----------------------------------------------------------------------------------------------------------------------------------------

下面看看《Camel in Action》书中内容

Automating tasks (Timer and Quartz components)

自动化任务(定时器和Quartz组件)

Often in enterprise projects you’ll need to schedule tasks to occur either at a specified time or at regular intervals.

通常在企业项目中,您需要安排任务在指定的时间或定期进行。

Camel supports this kind of service with the Timer and Quartz components. 

Camel支持使用Timer和Quartz组件的这种服务。

The Timer component is useful for simple recurring tasks, but when you need more control of when things get started, the Quartz component is a must.

Timer组件对于简单的循环任务是有用的,但是当你需要更多的控制什么时候开始的时候,Quartz组件是必须的。

In this section, we’re first going to look at the Timer component and then move on to the more advanced Quartz component.

在本节中,我们将首先看看Timer组件,然后转到更高级的Quartz组件。

 

Using the Timer component使用Timer组件

The Timer component comes with Camel’s core library and uses the JRE’s built-in timer mechanism to generate message exchanges at regular intervals. 

Timer组件带有Camel的核心库,并使用JRE的内置定时器机制来定期生成消息交换。

This component only supports consuming, because sending to a timer doesn’t really make sense.

这个组件只支持消费,因为发送到一个定时器并没有什么意义。

As an example, let’s print a message stating the time to the console every 2 seconds.

The route looks like this:

作为一个例子,让我们每2秒打一条消息给控制台。

路线如下所示

from("timer://myTimer?period=2000").setBody().simple("Current time is ${header.firedTime}").to("stream:out");

The timer URI is configuring the underlying java.util.Timer to have the name myTimer and an execution interval of 2000 milliseconds.

计时器URI正在配置底层的java.util.Timer,名称为myTimer,执行间隔为2000毫秒。

TIP When the value of milliseconds gets large, you can opt for a shorter notation using the s, m, and h keywords. 

提示当毫秒值变大时,可以使用s,m和h关键字选择较短的记法。

For example, 2000 milliseconds can be written as 2s, meaning 2 seconds. 90000 milliseconds can be written as 1m30s,and so on

例如,2000毫秒可以写成2秒,意思是2秒。 90000毫秒可以写成1m30s等等

下面看看Demo代码:

package com.camel.timer.server;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.ModelCamelContext;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class CamelTimerServer {

	public static final Logger logger = Logger.getLogger(CamelTimerServer.class);

	public static void main(String[] args) {

	// 日志
	PropertyConfigurator.configure("./conf/log4j.properties");
	PropertyConfigurator.configureAndWatch("./conf/log4j.properties", 1000);

	try {

	// 这是camel上下文对象,整个路由的驱动全靠它了。
	ModelCamelContext camelContext = new DefaultCamelContext();

	// 启动route
	camelContext.start();

	camelContext.addRoutes(new RouteBuilder() {

	@Override
	public void configure() throws Exception {
		from("timer://myTimer?period=2s")
		.setBody().simple("Current time is ${header.firedTime}")
		.to("log:CamelTimerServer?showExchangeId=true");
	}
	});

	// 通用没有具体业务意义的代码,只是为了保证主线程不退出
	synchronized (CamelTimerServer.class) {
		CamelTimerServer.class.wait();
	}

	} catch (Exception e) {
		e.printStackTrace();
	}

	}

}

运行之后的结果:

再来一个Demo

定时器 运行定时业务代码:

package com.camel.timer.server;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.ModelCamelContext;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class CamelTimerServer2 {

	public static final Logger logger = Logger.getLogger(CamelTimerServer2.class);

	public static void main(String[] args) {

	// 日志
	PropertyConfigurator.configure("./conf/log4j.properties");
	PropertyConfigurator.configureAndWatch("./conf/log4j.properties", 1000);

	try {

	ModelCamelContext camelContext = new DefaultCamelContext();

	camelContext.start();

	camelContext.addRoutes(new RouteBuilder() {

	@Override
	public void configure() throws Exception {

	from("timer://foo?period=2s").process(new Processor() {
		public void process(Exchange exchange) throws Exception {
			logger.info("Hello world  :" + System.currentTimeMillis());
		}
	});

	}
	});

	// 没有具体业务意义的代码,只是为了保证主线程不退出
	synchronized (CamelTimerServer2.class) {
		CamelTimerServer2.class.wait();
	}

	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}

	}

}

运行结果

How do I specify time period in a human friendly syntax

如何以人性化的语法指定时间段?

Available as of Camel 2.3

适用于Camel2.3

Some of the Camel components offers options to specify a time period, which must be entered in milli second as unit. 

This may be unfriendly to read as a human when the value is large such as 45min = 2700000 millis.

一些Camel组件提供了选项来指定一个时间段,必须以毫秒为单位进行输入。 

当数值很大时,如45分钟= 270万毫米,这可能是不友好的。

So in Camel 2.3 you can now configure any endpoint uri parameter using a String syntax, which at runtime will get converted to millis (long type).

因此,在Camel 2.3中,现在可以使用String语法来配置任何端点的uri参数,在运行时将会将其转换为millis(long类型)。

You can use the following short syntax, which is most common to use:

您可以使用以下最常用的简短语法:

Syntax

Unit

h

hour

m

minute

s

second

So for example the Timer endpoint can be configured as follows

因此,例如,定时器端点可以配置如下

from("timer:foo?period=45m").to("log:foo");

You can mix and match the units so you can do this as well:

你可以混合和匹配单位,所以你也可以这样做:

from("timer:foo?period=1h15m").to("log:foo");
from("timer:bar?period=2h30s").to("log:bar");
from("timer:bar?period=3h45m58s").to("log:bar");

However you can also use long syntax

但是,你也可以使用长的语法

Syntax

Unit

hour or hours

hour

minute or minutes

minute

second or seconds

second

 

from("timer:foo?period=45minutes").to("log:foo");

参考来源:

http://www.pretechsol.com/2014/07/camel-timer-example_85.html

http://camel.apache.org/timer.html

http://camel.apache.org/how-do-i-specify-time-period-in-a-human-friendly-syntax.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值