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?
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.
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.
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.
Use a ServletContextListener configured in your web.xml. Write the code that kicks off the timer in the contextInitialized method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With