Call method at server startup

I am trying to call a method when starting my application. The goal is to start a timer that does a specific job at specific intervals. how can i call the helloworld function when running jboss 7.1 web application?

+7
source share
4 answers

Other than ContextListeners, you can also have a servlet in loading web.xml at startup:

<servlet> <servlet-name>mytask</servlet-name> <servlet-class>servlets.MyTaskServlet</servlet-class> ... <load-on-startup>1</load-on-startup> </servlet> 

This servlet can run your task using any means you need, for example, a link.

But you should not use this approach, imho.

Use a proven / lib structure like quartz or a similar tool. There are many problems / problems when starting and synchronizing tasks on web servers, and it is better to use some proven tool than to repeat the errors that these tools have already encountered and solved. It may take some time to understand, but to avoid many headaches.

Jboss himself has a toolkit for this purpose: scheduling and task management. Never used, therefore not recommended.

+4
source

If you want to run the code before your web application serves any of your clients, you will need a ServletContextListener.

Create your listener class

 import javax.servlet.*; public class MyServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent e) { //Call your function from the event object here } public void contextDestroyed(ServletContextEvent e) { } } 

Put the class in WEB-INF / classes

Place the <listener element in the web.xml file.

 <listener> <listener-class> com.test.MyServletContextListener </listener-class> </listener> 

Hope this helps.

+6
source

Check out the Quartz Scheduler . You can use CronTrigger to run at specific intervals. For example, every 5 minutes would look like this:

"0 0/5 * * * ?"

The idea is to implement the Job interface, which is the launch task, schedule it using SchedulerFactory / Scheduler , build Job and CronTrigger and run it.

Here is a very clear example.

+2
source

Use the ServletContextListener configured in your web.xml . Write the code that starts the timer in the contextInitialized method.

+1
source

All Articles