Timer

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.

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button