Thursday, December 13, 2012

How to keep the servlet continously running?

27 down vote accepted
Your problem is that you misunderstand the purpose of the servlet. It's intented to act on HTTP requests, nothing more. You want just a background task which runs once on daily basis. For that Quartz or even ScheduledExecutorService is perfect. This needs to be initiated by a ServletContextListener. Here's a kickoff example:
public class Config implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new UpdateCounts(), 0, 1, TimeUnit.DAYS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}
Where the class UpdateCounts look like this:
public class UpdateCounts implements Runnable {

    @Override
    public void run() {
        // Do your job here.
    }

}
To get the ServletContextListener to run, just register it in web.xml as follows:
<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
Or, when you're already on Servlet 3.0, just annotate it with @WebListener
@WebListener
public class Config implements ServletContextListener {}
 

 http://www.blogger.com/blogger.g?blogID=2583984764735864664#editor

No comments:

Post a Comment