Reputation: 3690
I have one plain .java class. In that class I'm using a Timer
class schedule method, to schedule a task.
The problem is I'm using a Java EE application, and I dont know where to intantiate this class; from a Servlet or any thing like that? I want to instantiate that class only once when my application goes up.
Upvotes: 3
Views: 429
Reputation: 765
public class YourServlet extends HttpServlet {
private YourClass instance;
public void init() throws ServletException {
instance = new YourClass();
}
//code
}
By instantiating your class in the init method, you will make sure that your class will be instantiated only once, because in Java EE applications, Servlets are loaded into the server memory only once.
Upvotes: 1
Reputation: 7253
In Quartz -a popular scheduler- is a common practice to configure Jobs in a the init method of a Servlet with the load-on-startup attribute set to true:
From this article, in web.xml you should do this:
<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<display-name>Quartz Initializer Servlet</display-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
And then conigure Jobs in your servlet:
public class QuartzServlet extends GenericServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
// And continue with your configuration
PS: I strongly recomend you to use Quartz
Upvotes: 0
Reputation: 597124
You probably need a ServletContextListener
and its method contextInitialized(..)
. It is invoked once, when your application is initialized.
You map the listener with either @WebListener
or with <listener><listener-class>..</...>
in web.xml
Upvotes: 4