Home » Enterprise Java » ejb3 » Timer » Use Timer service example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Use Timer service example

This is an example of how to use the javax.ejb.TimerService in an EJB. 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, and EJB 2.x entity beans to be registered for timer callback events at a specified time, after a specified elapsed time, after a specified interval, or according to a calendar-based schedule.

Here, we shall show you how to create an EJB implementation with the TimerService interface.

Create the EJB implementation class.

The CalculatorService is an EJB implementation class that is a stateless session bean with a few methods. It is annotated with the javax.ejb.Stateless annotation. The class has a default public constructor. The TimerService of the enterprise bean container enables you to schedule timed notifications for all types of enterprise beans except for stateful session beans. When a timer expires (goes off), the container calls the method annotated @Timeout in the bean’s implementation class. The @Timeout method contains the business logic that handles the timed event. Methods annotated @Timeout in the enterprise bean class must return void and take a javax.ejb.Timer object as the only parameter. They may not throw application exceptions.

The CalculatorService has a local interface that defines the bean’s business and life cycle methods, decorated with the @Local annotation. It also has a remote interface decorated with the @Remote annotation, that can run on a different machine and a different Java virtual machine (JVM) than the CalculatorService.

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

@Stateless
public class CalculatorService implements CalculatorServiceLocal, CalculatorServiceRemote {

    @Resource
    TimerService timerService;
    
    public CalculatorService() {
    }

    @Timeout
    public void expire(Timer timer) {

  long[] timerInfo = (long[]) timer.getInfo();

  System.out.println("Timer expired! Adding " + timerInfo[0] + "+" + timerInfo[1] + "=" + (timerInfo[0] + timerInfo[1]));
    }
    
    @Override
    public void addAsync(long i, long j) {

  // We create a timer that expires 1 second after the addAsync method invocation

  timerService.createTimer(new Date(System.currentTimeMillis() + 1000), new long[] {i,j});
    }
    
    @Override
    public long add(long i, long j) {

  return (i + j);
    }

    @Override
    public double divide(long i, long j) {

  return ((double)i / j);
    }

    @Override
    public long multiply(long i, long j) {

  return (i * j);
    }

    @Override
    public long subtract(long i, long j) {

  return (i - j);
    }
    
}

The EJB local interface (suitable for in VM communication)

package com.javacodegeeks.snippets.enterprise;

import javax.ejb.Local;

@Local
public interface CalculatorServiceLocal {

    public void addAsync(long i, long j);
    public long add(long i, long j);
    public long subtract(long i, long j);
    public long multiply(long i, long j);
    public double divide(long i, long j);
    
}

The EJB remote interface (suitable for intra VM communication)

package com.javacodegeeks.snippets.enterprise;

import javax.ejb.Remote;

@Remote
public interface CalculatorServiceRemote {

    public void addAsync(long i, long j);
    public long add(long i, long j);
    public long subtract(long i, long j);
    public long multiply(long i, long j);
    public double divide(long i, long j);
    
}

The application.xml file describing the modules in the .ear archive

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/j2ee" 


 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  


 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application_1_4.xsd"


 version="1.4">
  <display-name>Calculator Application</display-name>

  <module>
     <ejb>calculatorServiceEJB3.jar</ejb>
  </module>

</application>

The structure of the .ear archive

calculatorApp.ear
 |
 |_calculatorServiceEJB3.jar
 |   |_com
 |   |  |_javacodegeeks
 |   |     |_snippets
 |   |
  |_enterprise
 |   |
     |_CalculatorService.class
 |   |
     |_CalculatorServiceLocal.class
 |   |
     |_CalculatorServiceRemote.class
 |   |_META-INF
 |
 |_META-INF
    |_application.xml

Run the application using a client

In CalculatorServiceClient we connect to JBoss naming service running on local host and on default port 1099. We use the Context to set the configuration for the JBoss server, such as Context.INITIAL_CONTEXT_FACTORY, Context.PROVIDER_URL and Context.URL_PKG_PREFIXES. We get the bean using the lookup(Name name) method of Context to invoke its methods.

package com.javacodegeeks.snippets.enterprise;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;


public class CalculatorServiceClient {

    public static void main(String[] a) throws Exception {


  /*

   * Connecting to JBoss naming service running on local host and on

   * default port 1099 the environment that should be created is like the

   * one shown below :

   */

  Hashtable env = new Hashtable();

  env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");

  env.put(Context.PROVIDER_URL, "jnp://localhost:1099");

  env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");

  

  Context ctx = new InitialContext(env);

  

  CalculatorServiceRemote calculatorService = (CalculatorServiceRemote) ctx.lookup("calculatorApp/CalculatorService/remote");

  

  long i = 10;

  long j = 3;

  

  calculatorService.addAsync(i, j);

    }

}

Output:

Timer expired! Adding 10+3=13

 
This was an example of how to use the TimerService in an EJB.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of