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 {}
No comments:
Post a Comment