views:

1209

answers:

2

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  A: 

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.

duffymo
In the Sun example, the timer will be created in the business method of an enterprise bean. So I would need to write a client class for this stateless session bean, create an instance of this client in a startup servlet, and use it to call the timer creation method.
mjustin
Yes. It's reasonable to assume that you've already got a servlet of some kind in your Java EE web app. Add the code into its init() method.
duffymo
A: 

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.sun.com/kensaks/entry/application_startup_shutdown_callbacks

mjustin