问题
For a background job which I would like to run in a J2EE container, I found the suggestion to create a startup servlet and use the Timer Service API to create a managed Timer (in the answers for What tools are there for timed batch processes in J2EE?).
To create a timer, I need a context which implements the timer API. (Example)
In the Servlet class, I override the init method, but it has only access to a ServletContext, but not to a SessionContext. A ServletContext does not have methods to create timers, so I am stuck here.
How can I access the J2EE timer service in the startup code of a servlet?
回答1:
Whenever I hear timer job, I can't help but think that this should be separated from a Java EE app server. You can use something like Quartz, or an operating system scheduled task, or a batch manager like AutoSys, but embedding it into a servlet seems like a misuse of servlets to me.
Java EE 5 containers have a TimerService that's an EJB. Perhaps this will help you sort it out.
回答2:
Instead of using the Servlet startup code (which will be executed after every redeployment) I found it cleaner to start timers in the startup of the EJB. With EJB 3.1 and Singleton EJB this now is possible with much less code:
http://blogs.oracle.com/kensaks/entry/application_startup_shutdown_callbacks
来源:https://stackoverflow.com/questions/1024081/how-can-i-use-the-j2ee-timer-service-api-in-the-servlet-startup-code