The Java EE 6 Tutorial, Volume I

Automatic Timers

Automatic timers are created by the EJB container when an enterprise bean that contains methods annotated with the @Schedule or @Schedules annotations is deployed. An enterprise bean can have multiple automatic timeout methods, unlike a programmatic timer where there can only be one method annotated with the @Timeout annotation in the enterprise bean class.

Automatic timers can be configured through annotations or through the ejb-jar.xml deployment descriptor.

The @Schedule and @Schedules Annotations

Adding a @Schedule annotation on an enterprise bean marks that method as a timeout method according to the calendar schedule specified in the attributes of @Schedule.

The @Schedule annotation has elements that correspond to the calendar expressions detailed in Creating Calendar-Based Timer Expressionsand the persistent, info, and timezone elements.

The optional persistent element takes a boolean value, and is used to specify whether the automatic timer should survive a server restart or crash. By default, all automatic timers are persistent.

The optional timezone element is used to optionally specify that the automatic timer is associated with a particular time zone. If set, this element will evaluate all timer expressions in relation to the specified time zone, regardless of the time zone in which the EJB container is running. By default, all automatic timers set are in relation to the default time zone of the server.

The optional info element is used to set an informational description of the timer. A timer's information can be retrieved later using Timer.getInfo.


Example 16–16 Setting an Automatic Timer Using @Schedule

The following timeout method uses @Schedule to set a timer that will expire every Sunday at midnight:

@Schedule(dayOfWeek="Sun", hour="0")
public void cleanupWeekData() { ... }

The @Schedules annotation is used to specify multiple calendar-based timer expressions for a given timeout method.


Example 16–17 Setting Multiple Automatic Timers for a Timeout Method Using @Schedules

The following timeout method uses the @Schedules annotation to set multiple calendar-based timer expressions. The first expression sets a timer to expire on the last day of every month. The second expression sets a timer to expire every Friday at 11:00 PM.

@Schedules ({
    @Schedule(dayOfMonth="Last"),
    @Schedule(dayOfWeek="Fri", hour="23")
})
public void doPeriodicCleanup() { ... }