Stateless session beans and message-driven beans (another type of EJB discussed in the next chapter) can have a method that is executed automatically at regular intervals. This functionality is useful in case we want to execute some logic periodically (once a week, every day, every hour, etc.) without having to explicitly call any methods. This functionality is achieved by the EJB timer service.
In order to use the EJB timer service, an instance of javax.ejb.TimerService
must be injected into the EJB via the @Resource
annotation. This object will be used to create and cancel timers in two different methods in the EJB. Finally, the EJB must have a method to be invoked when the timer expires. This method must be decorated with the @Timeout
annotation. The following example illustrates how to use the EJB timer service.
package com.ensode.ejbtimer.ejb; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.annotation.Resource; import javax...