Java Reference
In-Depth Information
TimerService timerService;
public void setTimer(){
ScheduleExpression expression = new ScheduleExpression();
expression.second("*/10").minute("*").hour("*");
timer = timerService.createCalendarTimer(
new ScheduleExpression().second("*/10").minute("*").hour("*"));
}
@Timeout
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void performTask() {
System.out.println("Simple Task performed");
}
}
Beans that use container‐managed transactions set the transitions attribute on the method annotated
@Timeout . Transactions are designated Required or RequiresNew . The transaction is started before
w
the method is called. If the transaction is rolled back, the @Timeout method is called again.
SUMMARY
In this chapter, you have seen how to create automatic and programmatic timers and how they
behave within a transaction. Timers can be quite useful when a cron‐like job needs to run without
disturbing the main business logic. You can see examples of timers in many projects and in almost
all programming languages. The automatic timer is created by annotating a method with either
@Schedule or @Schedules and hard‐coding timer values as attributes of the annotations by
declaring them in the ejb‐jar.xml deployment descriptor. Programmatic timers are created by the
application code and can change their values at run time.
The timer type you choose to solve your problem will depend largely on whether the frequency
of the event will change based on business logic (client services) or technical requirements
(repopulating a cache). The latter would best be served with a programmatic timer, whereas the
former would benei t most from an automatic timer.
Timers are persisted by default to guard against server shutdowns and crashes and can be serialized
in a database and later retrieved. Timers take part in a transaction and are fully rolled back with the
transaction. It became a little easier to manage timers in EJB 3.2; you can retrieve all active timers
in a collection and call timer methods on each instance.
With the new achievements on Java EE, timers became solid and capable, leaving most third‐party
frameworks obsolete.
EXERCISES
1. Write a cache that repopulates a map from a database. Set the timer service to i re at 3 a.m.,
calling the repopulate method of the cache.
2. Develop a programmatic timer that sends a notii cation to a client when his subscription is up
for renewal.
 
Search WWH ::




Custom Search