led to the invention of one of the most important devices of modern life: the alarm clock. Today
even basic cell phones and i tness trackers offer alarms that you can adjust to different times and
different days and even offer snooze options.
For a long time, neither Java SE nor Java EE offered a built‐in solution for time‐based operations.
This lack of support was i lled with community‐led open source.
Traditionally, timer‐based tasks would have been scheduled using a third‐party tool such as
1 but such a tool tends to be tricky to use. Third‐party tools require you to download
and install a library, implement interfaces, and coni gure XML i les. They're anything but
Fortunately for you and partly because of the difi culty faced by developers trying to use
third‐party libraries, a scheduling facility was introduced into the EJB 2.1 specii cation.
This timer service satisi ed the simplest use case scenarios. And for those complicated cases, there was
still Quartz. Indeed, Quartz almost became the de facto standard of time‐based operations in Java.
There is no default implementation for timers in Java SE. You can use Quartz in both Java SE
and Java EE, but Quartz usage is a separate topic beyond this topic. So this chapter skips the Java
implementation and moves on to Java EE.
Advancements were made in the EJB 3.2 specii cation (the latest release) to the timer service.
Introduced were the @Schedule and @Schedules annotations and cron‐like calendar expressions.
Now all but the most exceptional use case scenarios are satisi ed. The timer service runs in the
container as a service and registers Enterprise JavaBeans (EJB) for callbacks. It tracks the timers that
exist and their schedules, and it even takes care of persisting the timer in case a server shuts down or
crashes. The only thing the developer needs to do now is schedule the timer.
The timer service has been through a long development cycle. An overview of the advancements is
summarized in Table 10-1.
TABLE 10-1: Timer Servi ce Development
EJB 2.1 Java 1.4
The ejbTimer implements the TimedObject interface.
The TimerService is accessed through the EJBContext method.
The business logic must be in the ejbTimeout method.
EJB 3.0 Java 5
The TimerService object is injected via direct injection using the
annotation @Resource .
The business logic must be placed in a method annotated with @Timeout .
Schedule set by specifying a date, duration, or ScheduleExpression
object or an XML coni guration i le.
Referred to as programmatic timers in Java EE 6.