tags:

views:

107

answers:

4

Hi,

I have a Java servlet program which it starts when tomcat starts. I have mentioned the program as load at startup. I am not using any HTTP request or response.

What I need is I need to run the program as a service or need to have auto refresh at certain interval of time. How to do that? Can someone assist me!

Thanks, Gopal.

A: 

tomcat does a auto refresh every time the .war file changes

Tobiask
A: 

I sometimes use a timer to periodically makes HTTP requests:

    timer = new Timer(true);
    timer.scheduleAtFixedRate(
        new TimerTask() {
            URL url = new URL(timerUrl);
            public void run() {
                try {
                    url.getContent();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        },
        period,
        period);
Maurice Perry
+1  A: 

I recommend you to use Quartz. You can define a scheduled job with quartz.

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzTest {
   public static void main(String[] args) {
     try {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();

        scheduler.shutdown();
      } catch (SchedulerException se) {
        se.printStackTrace();
      }
  }
}
rayyildiz
+3  A: 

Quartz is a great idea, but might be a bit of overkill depending on what you need. I think youre real issue is trying to cram your service into a servlet, when you aren't actually listening to incoming HttpServletRequests. Instead, consider using a ServletContextListener to start up your service, and a Timer, as Maurice suggested:

web.xml:

<listener>
    <listener-class>com.myCompany.MyListener</listener-class>
</listener>

And then your class looks like this:

public class MyListener implements ServletContextListener {

    /** the interval to wait per service call - 1 minute */
    private static final int INTERVAL = 60 * 60 * 1000;

    /** the interval to wait before starting up the service - 10 seconds */
    private static final int STARTUP_WAIT = 10 * 1000;

    private MyService service = new MyService();
    private Timer myTimer;

    public void contextDestroyed(ServletContextEvent sce) {
     service.shutdown();
     if (myTimer != null)
      myTimer.cancel();
    }

    public void contextInitialized(ServletContextEvent sce) {
        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
      public void run() {
       myService.provideSomething();
      }
        },STARTUP_WAIT, INTERVAL
      );
    }
}
gregcase
Quartz vs TimerTasker:Note that the Timer mechanism uses a TimerTask instance that is shared between repeated executions, in contrast to Quartz which creates a new Job instance for each execution.
ariso