Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call method on server startup [duplicate]

I am trying to call a method when my webapplication starts. The purpose is to kick-off a timer that does some work at defined intervals. how do i call a function helloworld when my jboss 7.1 web application starts up?

like image 639
user1438082 Avatar asked Mar 24 '13 00:03

user1438082


4 Answers

If you want to run some code before your web app serves any of your clients you 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

Put a <listener> element in the web.xml file.

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

Hope this helps.

like image 115
Karthik Rajah Avatar answered Oct 20 '22 05:10

Karthik Rajah


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

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

This servlet can start your task using whatever means you want, see for example this link.

But you shouldn't use that approach, imho.

Use a proven framework/lib like quartz or a similar tool. There are a lot of problems/issues in running and syncing tasks in web servers and it's better to use some proven tool than to repeat mistakes these tools already met and solved. It might take a little while to grasp but will avoid many headaches.

Jboss itself has some tooling for that purpose: scheduling and managing tasks. Never used so can't recommend.

like image 33
jagra Avatar answered Oct 20 '22 05:10

jagra


Check out Quartz Scheduler. You can use a CronTrigger to fire at defined intervals. For example, every 5 minutes would look like this:

"0 0/5 * * * ?"

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

There is a very clear example here.

like image 20
Bizmarck Avatar answered Oct 20 '22 04:10

Bizmarck


Use a ServletContextListener configured in your web.xml. Write the code that kicks off the timer in the contextInitialized method.

like image 35
adarshr Avatar answered Oct 20 '22 03:10

adarshr