Sometimes it is useful to create a timer as soon as the application is deployed. Many applications have actions that need to occur on a regular basis. Creating timers for these actions at application start up is a convenient way of addressing this need.
One way to achieve this is to use a singleton EJB. Here we will programmatically create a timer that generates a JVM memory report after the application has been deployed.
The steps to achieve the creation of timers in this fashion include:
We will create a singleton EJB and then use the @PostConstruct annotation with a method which creates the timer. In this method, we will also create an instance of the SystemReportManager
so we can get ready access to the report.
Create a singleton EJB called ReportsSingleton
. Details on how singletons work is found in the Singleton session bean and Using multiple singleton beans recipes of Chapter 2, Session Beans. Use the @Startup annotation to request immediate instantiation of the EJB when the application is loaded.
@Singleton @Startup public class ReportsSingleton { ... }
First, set up three instance variables for the application:
timerService
Use resource injection to create an instance of the TimerService
duration
A long value set to 1000 milliseconds specifying the delay before the report is generatedsystemReportManager
Use dependency injection to create an instance of the SystemReportManager
@Resource TimerService timerService; long duration = 1000; @EJB SystemReportManager systemReportManager;
Create a method called initialization
which returns void
and is passed void
. Add the @PostConstruct annotation to the method. In the method, add a println
method to show the method is executing. Next, use the createSingleActionTimer
method to create a timer.
@PostConstruct public void initialization() { System.out.println("ReportsSingleton initialization"); timerService.createSingleActionTimer(duration, new TimerConfig()); }
The last step is to create the @Timeout method. Name the method, timeout
, and use the getMemoryReport
to display the memory used.
@Timeout public void timeout(Timer timer) { System.out.println("timeout occurred"); System.out.println(" " + systemReportManager.getMemoryReport()); } }
Deploy the application. The output should appear similar to the following:
INFO: ReportsSingleton initialization
INFO: Loading application ReportsApplication#ReportsApplication-war.war at ReportsApplication-war
INFO: ReportsApplication was successfully deployed in 420 milliseconds.
INFO: timeout occurred
INFO: Total Memory: 235073536
Maximum Memory: 518979584
Free Memory: 91557120
Annotating the singleton with the @Startup annotation resulted in the creation of the singleton when the application was deployed. The @PostConstruct annotated method, initialization
, was executed after the singleton was created. Within this method we created a new timer event that executed one second later. The timeout
method was executed at that time.
18.117.146.155