Gopalakrishnan
Gopalakrishnan

Reputation:

Servlet Program as a service

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.

Upvotes: 0

Views: 230

Answers (4)

rayyildiz
rayyildiz

Reputation: 338

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();
      }
  }
}

Upvotes: 1

Greg Case
Greg Case

Reputation: 3240

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
      );
    }
}

Upvotes: 3

Maurice Perry
Maurice Perry

Reputation: 32831

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);

Upvotes: 0

Tobias
Tobias

Reputation: 7380

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

Upvotes: 0

Related Questions