call method on server startup [duplicate]

℡╲_俬逩灬. 提交于 2019-12-09 15:49:01

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/15593935/call-method-on-server-startup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!