Where to instantiate the class

I have one simple .java class. In this class, I use the class schedule method Timerto schedule a task.

The problem is that I am using the Java EE application and I do not know where to learn it. from a servlet or any similar thing? I want to instantiate this class only once when my application grows.

+3
source share
3 answers

You will probably need ServletContextListenerhis method as well contextInitialized(..). It is called once when your application is initialized.

You display the listener using @WebListeneror with <listener><listener-class>..</...>in web.xml

+4
source
 public class YourServlet extends HttpServlet {
 private YourClass instance;

 public void init() throws ServletException {
      instance = new YourClass();
 }
 //code
 }

init, , , Java EE .

+1

In Quartz, a popular scheduler is a common practice for setting tasks in the servlet init method 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 configure the 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 highly recommend you use Quartz

0
source

All Articles