...
Implementing timer components is similar to implementing Java-based components. References, properties, and resources may be injected and used when the timer is fired. However, since timer components are not invoked by clients, they do not implement a service interface. Rather, they implement java.lang.Runnable. When the timer is fired, its run() method will be invoked. The following is an example of a timer implementation that uses a JPA EntityManager to retrieve a list of records and invoke a notification service:
Code Block | ||||
---|---|---|---|---|
| ||||
@Component @Timer(type = TimerType.FIXED_RATE, fixedRate=10000) public class TimedComponent implements Runnable { @PersistenceContext(name="notifyEM") protected EntityManager entityManager; @Reference @Target("NotificationService") protected NotificationService service; public void run() { // use the entityManager to retrieve records ... List<Record> records = (List<Record>) entityManager.createQuery("").getResultList(); // iterate through the records and fire notifications for (Recordsrecord :records) { service.notify; } } } |
Timer components are can also configured in XML using the implementation.timer element:
...
Fixed rate fires a timer at the specified rate in milliseconds. A best effort will be made to maintain the rate over time. For example, the following timer will fire on average every 10 seconds:
Code Block | ||||
---|---|---|---|---|
| ||||
In Java:
@Timer(type = TimerType.FIXED_RATE, fixedRate=10000)
Or in XML:
<f3:implementation.timer class="org.foo.timer.TimedComponent" fixedRate="10000"/>
|
...
Repeat interval fires a timer according to the specified interval in milliseconds. For example, the following configures a timer to be triggered in intervals of 10 seconds:
Code Block | ||||
---|---|---|---|---|
| ||||
In Java:
@Timer(type = TimerType.INTERVAL, repeatInterval=10000)
Or in XML:
<f3:implementation.timer class="org.foo.timer.TimedComponent" repeatInterval="10000"/>
|
...
To create a create a dynamic firing timer, implement the nextInterval() method according to the following:
Code Block | ||||
---|---|---|---|---|
| ||||
@Timer(type = TimerType.RECURRING)
public class TransactionalTimedIntervalComponent implements Runnable {
public void run() {
}
public long nextInterval() {
return 100;
}
}
|
The above component can be configured in XML as follows:
Code Block | ||||
---|---|---|---|---|
| ||||
<component name="TrxTimerIntervalComponent">
<f3:implementation.timer poolName="TestPool" class="org.fabric3.tests.timer.TransactionalTimedIntervalComponent"/>
</component>
|
...
Fire once triggers the timer once at the specified time in milliseconds. This method of configuring a timer is likely to have limited use. The following shows how to configure a timer to fire once:
Code Block | ||||
---|---|---|---|---|
| ||||
In Java:
@Timer(type = TimerType.ONCE, fireOnce=10000)
In XML:
<f3:implementation.timer class="org.foo.timer.TimedComponent" fireOnce="...."/>
|
...