Using the Timer Service
Applications that model business work flows often rely on timed notifications. The timer service of the enterprise bean container enables you to schedule timed notifications for all types of enterprise beans except for stateful session beans. You can schedule a timed notification to occur at a specific time, after a duration of time, or at timed intervals. For example, you could set timers to go off at 10:30 AM on May 23, in 30 days, or every 12 hours.
When a timer expires (goes off), the container calls the method annotated
@Timeoutin the bean's implementation class. The@Timeoutmethod contains the business logic that handles the timed event.The Timeout Method
Methods annotated
@Timeoutin the enterprise bean class must returnvoidand take ajavax.ejb.Timerobject as the only parameter. They may not throw application exceptions.Creating Timers
To create a timer, the bean invokes one of the
createTimermethods of theTimerServiceinterface. (For details on the method signatures, see theTimerServiceAPI documentation.) When the bean invokescreateTimer, the timer service begins to count down the timer duration.The bean described in The timersession Example creates a timer as follows:
In the
timersessionexample,createTimeris invoked in a business method, which is called by a client.Timers are persistent. If the server is shut down (or even crashes), timers are saved and will become active again when the server is restarted. If a timer expires while the server is down, the container will call the
@Timeoutmethod when the server is restarted.The
Dateandlongparameters of thecreateTimermethods represent time with the resolution of milliseconds. However, because the timer service is not intended for real-time applications, a callback to the@Timeoutmethod might not occur with millisecond precision. The timer service is for business applications, which typically measure time in hours, days, or longer durations.Canceling and Saving Timers
Timers can be canceled by the following events:
If a method is invoked on a canceled timer, the container throws the
javax.ejb.NoSuchObjectLocalException.To save a
Timerobject for future reference, invoke itsgetHandlemethod and store theTimerHandleobject in a database. (ATimerHandleobject is serializable.) To reinstantiate theTimerobject, retrieve the handle from the database and invokegetTimeron the handle. ATimerHandleobject cannot be passed as an argument of a method defined in a remote or web service interface. In other words, remote clients and web service clients cannot access a bean'sTimerHandleobject. Local clients, however, do not have this restriction.Getting Timer Information
In addition to defining the
cancelandgetHandlemethods, theTimerinterface defines methods for obtaining information about timers:public long getTimeRemaining(); public java.util.Date getNextTimeout(); public java.io.Serializable getInfo();The
getInfomethod returns the object that was the last parameter of thecreateTimerinvocation. For example, in thecreateTimercode snippet of the preceding section, this information parameter is aStringobject with the valuecreated timer.To retrieve all of a bean's active timers, call the
getTimersmethod of theTimerServiceinterface. ThegetTimersmethod returns a collection ofTimerobjects.Transactions and Timers
An enterprise bean usually creates a timer within a transaction. If this transaction is rolled back, the timer creation is also rolled back. Similarly, if a bean cancels a timer within a transaction that gets rolled back, the timer cancellation is rolled back. In this case, the timer's duration is reset as if the cancellation had never occurred.
In beans that use container-managed transactions, the
@Timeoutmethod usually has theRequiredtransaction attribute to preserve transaction integrity. With this attribute, the EJB container begins the new transaction before calling the@Timeoutmethod. If the transaction is rolled back, the container will call the@Timeoutmethod at least one more time.The timersession Example
The source code for this example is in the
<INSTALL>/javaeetutorial5/examples/ejb/timersession/timersession-ejb/src/javadirectory.
TimerSessionBeanis a stateless session bean that shows how to set a timer. In the source code listing ofTimerSessionBeanthat follows, note thecreateTimerand@Timeoutmethods. Because it's a business method,createTimeris defined in the bean's remote business interface (TimerSession) and can be invoked by the client. In this example, the client invokescreateTimerwith an interval duration of 30,000 milliseconds. ThecreateTimermethod creates a new timer by invoking thecreateTimermethod ofTimerService.TimerServicewhich is injected by the container when the bean is created. Now that the timer is set, the EJB container will invoke thetimeoutmethod ofTimerSessionBeanwhen the timer expires--in about 30 seconds. Here's the source code for theTimerSessionBeanclass:package com.sun.tutorial.javaee.ejb; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerService; @Stateless public class TimerSessionBean implements TimerSession { @Resource TimerService timerService; private static final Logger logger = Logger .getLogger("com.sun.tutorial.javaee.ejb. timersession.TimerSessionBean"); public void createTimer(long intervalDuration) { Timer timer = timerService.createTimer(intervalDuration, "Created new timer"); } @Timeout public void timeout(Timer timer) { logger.info("Timeout occurred"); } }Building and Packaging timersession
In a terminal window, go to the
<INSTALL>/javaeetutorial5/examples/ejb/timersession/directory. To buildTimerSessionBean, type the following command:This runs the
defaulttask, which compiles the source files and packages the application into an EAR file located at<INSTALL>/examples/ejb/timersession/dist/timersession.ear.Deploying timersession
Now that the Java EE application contains the enterprise bean package and deploy the
TimerSessionBeanusingant:Running the Application Client
To run the application client, perform the following steps.
- In a terminal window, go to the
<INSTALL>/javaeetutorial5/directory.
examples/ejb/timersession/- Type the following command:
ant runThis task first retrieves the client JAR,
timersessionClient.jarto the dist directory, and then runs the client. This is the equivalent of running:
appclient -client TimerSessionAppClient.jar- In the terminal window, the client displays these lines:
Creating a timer with an interval duration of 30000 ms.The output from the timer is sent to the
server.logfile located in the<JAVA_EE_HOME>/domains/domain1/server/logs/directory.View the output in the Admin Console:
Alternatively, you can look at the log file directly. After about 30 seconds, open
server.login a text editor and you will see the following lines: