JBoss.org Community Documentation

Chapter 34. Introduction to timer service in EJB3

This example shows you how to access javax.ejb.SessionContext as well as using the EJB Timer Service. It also explains how callbacks work in EJB 3.0.

SessionContext injection :

The javax.ejb.SessionContext is injected using the @javax.annotation.Resource annotation. When the stateless bean instance is created the field will be initialized with the correct SessionContext. Take a look at org.jboss.tutorial.timer.bean.ExampleTimerBean

private @Resource SessionContext ctx;



Timeout Callbacks :

The rest of the bean example registers a timer with the EJB Timer service. In the EJB 2.1 specification it was required to implement an interface to get ejbTimeout callbacks. In JBoss EJB3, it is implemented as an annotation. All you have to define is a method annotated with javax.ejb.Timeout.

Building and Running

From the command prompt, move to the "timer" folder under the Section 1.3, “Set the EJB3_TUTORIAL_HOME”

Ant Users:

Make sure your JBossAS-5.x is running

$ ant
$ ant run

     [java] Timer scheduled to trigger after 5 seconds


Maven Users: Make sure the AS is not running.

$ mvn clean install -PRunSingleTutorial

On the server you will notice these logs:

INFO  [STDOUT] ---------------------
INFO  [STDOUT] Created a timer event to be triggered after 5000 milli seconds
INFO  [STDOUT] ---------------------
INFO  [STDOUT] ---------------------
INFO  [STDOUT] * Received Timer event: Hello World
INFO  [STDOUT] ---------------------