Timer

EJB Timer Service Example

1. Introduction

In this example we will show how to use EJB Timer Service . The EJB timer service is a container-provided service that allows the Bean Provider to register enterprise beans for timer callbacks to occur according to a calendar-based schedule, at a specified time, or at specified intervals.

2. Create a new EJB Module

Open NetBeans IDE, choose File > New Project .
In the New Project wizard, expand the Java EE category and select EJB Module as shown in the figure below. Then click Next.

Figure 1. Create new EJB Module
Figure 1: Create new EJB Module

You have to specify the Project Name, the Project Name and the Project Location in the appropriate text fields and then click Next.

2
Figure 2: Configure Project

In the next window , add the JEE Server and select the JEE version and click Finish.

Figure 3. Add Server
Figure 3: Add Server

3. Create a new Session Bean

Go to File -> New File -> Enterprises JavaBeans -> Session Bean or
Right-click the EJB module project and choose New > Session Bean .

Figure 4. Create new Session Bean
Figure 4: Create new Session Bean

Type TimerServiceDemo for the EJB Name and org.netbeans.example for the Package and Select Singleton for the Session Type.

Figure 5. Select Bean Type
Figure 5: Select Bean Type

When you click Finish, the IDE creates the session bean in the org.netbeans.example package in the EJB module and opens the class in the editor

Figure 6. Generated Bean Source
Figure 6: Generated Bean Source

4. TimerService Interface

The TimerService interface provides enterprise bean components with access to the container-provided Timer Service. The EJB Timer Service allows stateless session beans, singleton session beans, message-driven beans . To create a timer, we need to create TimerService object and use one of its createTimer() method. The Timer Service is accessed via dependency injection, through the getTimerService method of the EJBContext interface, or through lookup in the JNDI namespace.

5. Create Timer

5.1. Interval Timer

Create an interval timer whose first expiration occurs at a given point in time and whose subsequent expirations occur after a specified interval.

IntervalTimerDemo.java 

package org.netbeans.example;

import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

@Singleton
@LocalBean
@Startup
public class IntervalTimerDemo {

    @Resource
    private TimerService timerService;

    @PostConstruct
    private void init() {
        timerService.createTimer(1000, 2000, "IntervalTimerDemo_Info");
    }

    @Timeout
    public void execute(Timer timer) {
        System.out.println("Timer Service : " + timer.getInfo());
        System.out.println("Current Time : " + new Date());
        System.out.println("Next Timeout : " + timer.getNextTimeout());
        System.out.println("Time Remaining : " + timer.getTimeRemaining());
        System.out.println("____________________________________________");
    }

}
Output –
Info:   Timer Service : IntervalTimerDemo_Info
Info:   Current Time : Sat Jan 17 09:59:25 IST 2015
Info:   Next Timeout : Sat Jan 17 09:59:27 IST 2015
Info:   Time Remaining : 1997
Info:   ____________________________________________
Info:   Timer Service : IntervalTimerDemo_Info
Info:   Current Time : Sat Jan 17 09:59:27 IST 2015
Info:   Next Timeout : Sat Jan 17 09:59:29 IST 2015
Info:   Time Remaining : 1998
Info:   ____________________________________________
Info:   Timer Service : IntervalTimerDemo_Info
Info:   Current Time : Sat Jan 17 09:59:29 IST 2015
Info:   Next Timeout : Sat Jan 17 09:59:31 IST 2015
Info:   Time Remaining : 1997
Info:   ____________________________________________

5.2. Single Action Timer

Create a single-action timer that expires after a specified duration.

SingleActionTimerDemo.java

package org.netbeans.example;

import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

@Singleton
@LocalBean
@Startup
public class SingleActionTimerDemo {

    @Resource
    private TimerService timerService;

    @PostConstruct
    private void init() {
        TimerConfig timerConfig = new TimerConfig();
        timerConfig.setInfo("SingleActionTimerDemo_Info");
        timerService.createSingleActionTimer(5000, timerConfig); // after 5 seconds
        System.out.println("INIT Time : " + new Date());
    }

    @Timeout
    public void execute(Timer timer) {
        System.out.println("Timer Service : " + timer.getInfo());
        System.out.println("Execution Time : " + new Date());
        System.out.println("____________________________________________");   
    }

}
Output –
Info:   INIT Time : Sat Jan 17 10:06:09 IST 2015
Info:   TimerServiceExample was successfully deployed in 385 milliseconds.
Info:   Timer Service : SingleActionTimerDemo_Info
Info:   Execution Time : Sat Jan 17 10:06:14 IST 2015
Info:   ____________________________________________

5.3. Calendar Timer

The Timer Service allows a timer callback schedule to be expressed using a calendar-based syntax .

5.3.1. Calendar Timer – Programmatic

For calendar-based timers, the expiration of the timer is expressed as a javax.ejb.ScheduleExpression object, passed as a parameter to the TimerService.createCalendarTimer method. The ScheduleExpression class represents calendar-based timer expressions .

Create a session bean named CalendarProgTimerDemo.java with the following code:

CalendarProgTimerDemo.java

package org.netbeans.example;

import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.ejb.ScheduleExpression;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

@Singleton
@LocalBean
@Startup
public class CalendarProgTimerDemo {

    @Resource
    private TimerService timerService;

    @PostConstruct
    private void init() {
        TimerConfig timerConfig = new TimerConfig();
        timerConfig.setInfo("CalendarProgTimerDemo_Info");
        ScheduleExpression schedule = new ScheduleExpression();
        schedule.hour("*").minute("*").second("13,34,57");
        timerService.createCalendarTimer(schedule, timerConfig); 
    } 

    @Timeout
    public void execute(Timer timer) {
        System.out.println("Timer Service : " + timer.getInfo());
        System.out.println("Execution Time : " + new Date());
        System.out.println("____________________________________________");   
    }

}

Output –
Info:   Timer Service : CalendarProgTimerDemo_Info
Info:   Execution Time : Sat Jan 17 10:09:13 IST 2015
Info:   ____________________________________________
Info:   Timer Service : CalendarProgTimerDemo_Info
Info:   Execution Time : Sat Jan 17 10:09:34 IST 2015
Info:   ____________________________________________
Info:   Timer Service : CalendarProgTimerDemo_Info
Info:   Execution Time : Sat Jan 17 10:09:57 IST 2015
Info:   ____________________________________________
Info:   Timer Service : CalendarProgTimerDemo_Info
Info:   Execution Time : Sat Jan 17 10:10:13 IST 2015
Info:   ____________________________________________
Info:   Timer Service : CalendarProgTimerDemo_Info
Info:   Execution Time : Sat Jan 17 10:10:34 IST 2015
Info:   ____________________________________________

5.3.2. Calendar Timer – Automatic

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, which allows only one method annotated with the @Timeout annotation in the enterprise bean class.
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.

Create a session bean named CalendarAutoTimerDemo.java with the following code:

CalendarAutoTimerDemo.java

package org.netbeans.example;

import java.util.Date;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.ejb.Schedule;
import javax.ejb.Startup;
import javax.ejb.Timer;

@Singleton
@LocalBean
public class CalendarAutoTimerDemo {

    @Schedule(second="13,34,57", minute="*", hour="*")
    public void execute(Timer timer) {
        System.out.println("Executing ...");
        System.out.println("Execution Time : " + new Date());
        System.out.println("____________________________________________");   
    }

} 


Output –
Info:   Executing ...
Info:   Execution Time : Sat Jan 17 10:12:13 IST 2015
Info:   ____________________________________________

6. Download the NetBeans Project

Download the NetBeans project of this tutorial:

Download
You can download the full source code of this example here: TimerServiceExample.zip

jGauravGupta

Gaurav is a senior software engineer with a passion for learning. He is an evangelist of netbeans & new technologies and author of JPA Modeler , jBatch Suite etc . He loves to go beyond the same old day to day work and find new and innovative ways to do the same things more effectively.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button