Sunday 8 June 2014

Examples of EJB 3.1 TimerService - Automatic Timers


An automatic timer typically suits for doing either an end of day kind of processing or for a purging activity.
Here is a simple example of an EJB 3.1 Timer to suit such a typical requirement.

In this example, it is assumed that the application have a SessionBean facade(s) which have all the business methods. A SessionBean facade is required for making use of the container managed persistence context in the business methods. The timer just invokes the relevant business method based on the timer schedule expiration.

package com.prasune.ejb.timer;

import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timer;

import com.prasune.ejb.persistence.JPASessionFacade;


@Stateless(name = "AutomaticTimer")
public class AutomaticTimerBean {
   
    @EJB
    private JPASessionFacade jpaSessionFacade;

    public AutomaticTimerBean()
    {
    }
   
    @Schedule(dayOfWeek="*", hour="0", persistent=true,
            timezone="UTC")
    public void processEOD(Timer timer)
    {      
        jpaSessionFacade.dmlOperation();
    }
}

Our example Automatic Timer executes the specified SessionBean facade business method every day at 12:00:00 a.m midnight.

@EJB annotation is used by the JEE server for injecting the SessionBean facade for calling the relevant business method.

@Schedule annotation has elements that corresponds to chrone job like calendar expression detailed at Understanding EJB Timer Service 3.1. In our example the timer schedule is to execute every day at 12:00:00 a.m midnight.

Elements of @Schedule annotation: @Schedule has a persistent element which is optional. This is by default true. This means the schedule of the timer is persisted and not specific to JVM and hence it should survive a server crash. There is also a time zone element to specify the time zone in which the timer schedule needs to be considered. By default, the time zone of the server is considered.

@Schedules annotation can be used to specify multiple @Schedule child annotations for the same method for various types of schedule. For example: 
@Schedules ({
    @Schedule(dayOfMonth="1"),
    @Schedule(dayOfWeek="Wed", hour="4")
})
The above schedule means the timer should execute on 1st of every month and every wednesday at 4:00:00 a.m.

Packaging and Deployment

Packaging and deployment of an EJB 3.1 Timer is very simple. The class file needs to be in a jar file with the correct directory structure of the package and the jar file can be directly deployed on any JEE server supporting EJB 3.1. The vendor specific ejb-jar.xml are optional and annotations are sufficient for the JEE server to identify the class as EJB Timer.

No comments:

Post a Comment