Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java EE: Working with Timer Service Design Pattern

See in this article what is the Timer Service Design Pattern, what are the new features introduced in the API and how we can implement it in the new Java EE 7 platform

The Timer Service is not referenced in the classic book design patterns such as the GoF book. However, this programming model is widely used and used in current applications of Java EE platform platform.

A large part of the enterprise applications need to perform tasks based on a schedule of events or at a scheduled time. This task can be, for example, the generation of weekly reports containing user activities, sending a client an email reminder, among other tasks that can vary from simple to complex. Overall, the Timer Service allows developers to schedule events at specific times or at regular intervals within the Java EE platform.

The rest of the article we will see how to implement this standard on the new Java EE 7 platform.

Standard Timer Service

Java EE and Java SE platforms did not offer embedded solutions for operations based on time. However, some tools developed by third parties permitted this type of application development, for example, Quartz tool that is still widely used mainly with Java SE environment. However, these tools for operations based on time has not allowed a more direct development, as well as having to download the library, install the library, implement the interfaces and still had to configure XML files.

From the EJB 2.1 specification introduced the timer service (or clock), but in Java SE yet there is no timer service can be used Quartz which is used both Java SE platform and the Java EE platform.

More features and enhancements have been added in the EJB 3.2 specification (latest release) to the Timer Service which made it even more simple and robust. Among the innovations has been the introduction of notes @Schedule and @Schedules in addition expressions additions.

The Timer Service runs on a container as a service and registers the Enterprise JavaBeans (EJB) for callbacks (callbacks methods). It tracks timers that exist and their respective schedules, and also continues the timer if a shut down or a server failure.

In this case, the only thing that the developer needs to know is to schedule the task.

The Timer Service has undergone several improvements over time from the EJB 2.1 through the EJB 3.0, EJB 3.1 and EJB 3.2.

In the next section we will see how to implement the Timer Service in Java EE 7 platform.

Implementing Timer Service in the Java EE platform

There are two types of timers in Java EE 7 platform, they are: the Automatic timers and Programmatic timers.

Automatic timers are configured by deploying (deployment) of an Enterprise Java Bean (EJB) that contains a method annotated with @Schedule or @Schedules. The annotated method is invoked by the container scheduler at specified times or intervals of time defined by the arguments of the notes. Such methods are referred to as callback methods (or callback methods). The timer starts counting as soon as the EJB is deployed, ie, how it is done deploy EJB.

A programmatic timer in turn is configured at run time for a method call on the business logic. The timer can be configured dynamically and invoked at any time. Therefore, the timer starts when the programming logic to determine that it should start.

In the next sections will be explained the differences between automatic and program timers.

Automatic timers

Any method annotated with @Schedule is called by the container which in turn applies the settings specified in the attributes of annotation.

Here in Listing 1 is an example of use of @Schedule note with some of its attributes.

Listing 1. Example usage of @Schedule note

 @Schedule(second="*/1", minute="*", hour="*")
  public void executeTask() {
           System.out.println("Task executed with success!");

In this code snippet can be seen that the executeTask method is annotated with @Schedule indicating that the container should set a timer in the deployment of this method is based on the values set in the attributes of annotation.

In the above example the expression contained in each of the attributes indicates that the container will invoke the method executeTask once every second.

By default, all the timers are persisted and restored after the shutdown or lock a server. If the optional attribute "persistent" is set to "false" the timer is reset on server restart. Two additional attributes can be configured, they are: "info" and "timezone." The attribute "info" allows a developer to provide a description when made a call to the method "getInfo" the Timer interface. If the attribute "timezone" is set, this zone will be respected when the timer runs. Otherwise, the time server time will be used.

Here in Listing 2 is an example of using the attribute "timezone" and attribute "info".

Listing 2. Example use of info attributes and timezone in the Schedule

@Schedule (Hour = "23" minute = "59" timezone = "CET", info = "Generate Report Night.")
  public void executeTask() {
           System.out.println ( "Task successfully executed!");

In the previous code "executeTask" method is called ace 23:59 in the time zone of Central Europe, thus disregarding the server time zone in which the deployment was done. A call to the "getInfo" returns the text set in the attribute "info", or would be obtained in return "Gera Night Report."

They can also be configured using more complete timers @Schedules annotation (now no more @Schedule) through the use of multiple expressions as shown in the example of Listing 3.

Listing 3. Example of use of the Schedules

  @Schedules ({
           @Schedule (DayOfMonth = "1"),
           @Schedule (DayOfWeek = "Mon, Tue, Wed, Thu, Fri" hour = "8")
  public void executeTask() {
           System.out.println ( "Task successfully executed!");

As the example shown the timer is triggered on the first day of each month and from Monday to Friday at 08:00.

Already the Listing 4 code shows a complete example of an automatic timer.

Listing 4. Complete example of a self-timer

 package com.mrbool.timer;
  import javax.ejb.Schedule;
  import javax.ejb.Schedules;
  public class TimerExample {
                     @Schedule(dayOfMonth = "1"),
                     @Schedule(dayOfWeek = "Mon,Tue,Wed,Thu,Fri", hour = "8")
           public void executeTask() {
                     System.out.println("Task executed with success!");

A disadvantage of the self-timer is that your schedule is set at the time of deployment (deploy) and can not be changed while the application is running. Fortunately there is a solution to this situation through a programmatic timer. A programmatic timer lets you set the schedule at any time during execution, this timer will be better discussed in the next section.

Programmatic timers

Programmatic timers are created at run time by calling one of its methods "create" interface. The example in Listing 5 shows one of the methods "create" available in the interface.

Listing 5. Example of use of the method "createTimer" to create a programmatic timer

 public void setTimer() {
           timerService.createTimer(30000, "New Timer");

When setTimer method is invoked by the application has to create a timer that calls a "timeout" method in the same bean after the specified length of 30,000 milliseconds.

A method "timeout" is identified by @Timeout annotation and must meet certain requirements such as: (i) it should not throw exceptions or return a value, (ii) does not need to receive parameters, but if you get this kind should be the javax. ejb.Time and finally (iii) there must be only one method "timeout".

Here in Listing 6 is an example of a method annotated with @Timeout that meets the specified requirements.

Listing 6. Example of using a timeout method

  public void exemploTimeout() {
           System.out.println("Task executed with success!");

The CDI container (Context Dependency Injection) injects a reference to the TimerService in an instance variable annotated @Resource. The following is an example of the container injecting into the TimerService instance variable.

  TimerService timerService;

The previous code could be placed together in a single bean where the application calls the setTimer method and a method "timeout" that will be called after 30 seconds. Here in Listing 7 is an example of how we could implement this programmatic timer.

Listing 7. Example implementation of a programmatic Timer

  package com.mrbool.timer;
  import javax.annotation.Resource;
  import javax.ejb.Timeout;
  import javax.ejb.TimerService;
  public class TimerExampleProgramatic {
           TimerService timerService;
           public void setTimer(){
                     timerService.createTimer(30000, "New Timer.");
           public void executeTask() {
                     System.out.println("Task executed with success!");

There are the total four methods of creating timers in TimerService interface with a total of ten signatures.

In the following example has the createIntervalTimer method that creates a timer that is triggered on a certain date and then every ten seconds:

createIntervalTimer (new Date(), 10000, new TimerConfig());

In the next example has the createSingleActionTimer method that creates a timer that fires after a second.

createSingleActionTimer(1000, new TimerConfig());

In the example below you have the createTimer method that creates a timer that fires after 30 seconds:

createTimer (30000, "New Timer Programmatic");

In the example below you have the createCalendarTimer method that creates a timer that fires every 10 seconds:

createCalendarTimer(new ScheduleExpression().second("*/10").minute("*").hour( "*"));

All methods beyond method "createCalendarTimer" can receive as the first parameter a duration in milliseconds or a date. This sets the point at which the timer is triggered. Here in Listing 8 an example.

Listing 8. Example of use createSingleActionTimer creation method

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy ‘at’ HH:mm");
  Date date = formatter.parse("01/07/2015 at 17:00");
  timerService.createSingleActionTimer(date, new TimerConfig());

In this example, the method "timeout" is triggered at 17:00 on 01 July 2015.

If a timer is required createCalendarTimer can use the method. This method receives a ScheduleExpression that is setting using expressions as discussed in the next section. Here in Listing 9 an example.

Listing 9. Example of using expressions with ScheduleExpression.

 ScheduleExpression expression = new ScheduleExpression();

In this code, the schedule is configured to fire every ten seconds every minute and every hour.

All methods of creating return a Timer object that represents the timer. The Timer object has the method "GetHandle" which returns a serialized identifier for the timer. The object identifier can be kept in a database or memory. Subsequently we could retrieve the object identifier and returning a reference to the timer invoking the method "getTimer". With this object in hand, you can retrieve useful information on the timer. Details on the timer schedule can be retrieved using the "getSchedule" which returns a "ScheduleExpression" object, where you can use the getter methods for each attribute. For example, the "GetMinute()" method returns the value set for the attribute "minute".

The "getNextTimeout" method returns the point when the timer is triggered, while the method "getTimeRemaining" returns the milliseconds before the expiry of the timer. The "isCalendarTimer" method returns "true" if the timer has been set for a "ScheduleExpression" object, but should be called the "getSchedule" method to determine if the timer has been set, otherwise the "isCalendarTimer" method throws an IllegalStateException exception. To determine information about the persistent state of the timer method is used "isPersistent". Similarly one can obtain weather information by calling the "getInfo". The timers are automatically canceled when they expire. To cancel scheduled timers simply call the method "cancel" on the Timer object.

Expressions Timers

Programmatic timers and automatic timers can use the attributes to set the timer. In automatic timers can configure the attributes of the notes, while programmatic timers use the methods of ScheduleExpression class.

There are some restrictions that must be met for each of the attributes. The "second" attribute accepts one or more seconds in a minute with values between 0 and 59, the attribute "minute" accepts one or more minutes in an hour with values between 0 and 59, the attribute "hour" accepts one or more hours in a day with values between 0 and 23, the attribute "dayOfWeek" takes one or more days within one week with values between 0 and 7 and 7 Sunday, "dayOfMonth" attribute takes one or more days within a month with values between 1 and 31 apart to accept the value -1 to -7 respect to days from the end of the month, last day to the last, or 1st, 2nd, 3rd, etc., and finally values between Sun and Sat, the attribute "month" accepts one or more months in a year with values between 1 and 12 and with values between Jan and Dec, and finally, the "year" attribute accepts a year like 2014, 2015 etc.

The default value for the attribute values is zero for the time and asterisk to the attributes that are not numerical. The asterisk is a placeholder for all possible values for an attribute. To set a timer that is triggered every time can be used, for example, the expression hour="*", the same goes for the hour method ScheduleExpression class that would be used the method "hour("*")". Another possibility is to use a list or a range as the expression dayOfMonth="1, 15, last" to set the trigger in the first, fifteenth and last day of each month. In turn the expression hour="8-18" is every hour from 08:00 until 18:00. To specify intervals and increase them with a starting point could use the expression hour="8/1" that triggers every hour starting at 08:00 different expression hour="*/12" that triggers every 12 hours.

You can also just set intervals for seconds, minutes and hours. Thus, the expression second="10" fires every ten seconds, hour="2" shot every two hours, minute="15" triggers every 15 minutes dayOfWeek="Mon, Fri" fires every second and Friday midnight, the expression dayOfWeek="0-7" hour="8" fires every day at 8 am, dayOfMonth="-7" shoot six days before the end of each month at midnight, the expression dayOfMonth="1st Mon" hour ="22" triggers on the first Monday of each month at 10 pm, a month = "Mar" expression, dayOfMonth="15" fires on the fifteenth day of March next year, expression year="2015", month="May" fires the first of March 20015 midnight.

In EJB 3.2, you can access all active timers in the EJB module. This includes programmatic and automatic timers.

In Listing 10 is an example of how you can implement this functionality in the EJB.

Listing 10. Example of how to retrieve and manipulate timers

 package com.mrbool.timer;
  import java.util.Collection;
  import javax.annotation.PostConstruct;
  import javax.annotation.Resource;
  import javax.ejb.Singleton;
  import javax.ejb.Startup;
  import javax.ejb.Timer;
  import javax.ejb.TimerService;
  public class AllTimersExample {
           TimerService timerService;
           public void gerenciaTimeres(){
                     Collection<Timer> timers = timerService.getAllTimers();
                     for(Timer t : timers){
                              System.out.println("Timer info: " + t.getInfo());
                              System.out.println("Time left: " + t.getTimeRemaining());
                              // cancel the Timer

Note that the bean is instantiated at startup and gerenciaTimeres method is called. In this method it is recovered a collection of all active timers and after that iterates on the entire collection printing timer information and the number of milliseconds remaining to expiration of the programmed timer. Finally, it cancels the timer.


[1] Erich Gamma, Ricard Helm, Ralph Johnson, John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994).

[2] Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra. Head First Design Patterns. O'Reilly Media, 2004.

[3] Murat Yener, Alex Theedom. Proffesional Java EE Design Patterns. Wrox, 2015.

Fabrí­cio Galdino is a software expert and has worked with IT analysis and business development for more than five years. It has extensive experience with testing, back and front-end technologies.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login