Background timer task in JSP/Servlet web application

MalTec picture MalTec · Mar 18, 2011 · Viewed 24.3k times · Source

I want to retrieve from subscription and store feeds to DB from subscription after every 6 hours. I want to have a timer thread in background to accomplish this task.

What's the best way? A normal timer thread or Quartz API?

Answer

BalusC picture BalusC · Mar 18, 2011

To start, I wouldn't use JSP for this. There it is not for.

When you're on Java EE 5, use the container-provided jobscheduling APIs for this. Further detail depends on the container you're using. JBoss AS 5 for example ships with Quartz out the box. Or when you're using a framework on top of JSP/Servlet which offers jobscheduling APIs, like as Spring, then you should use it.

If there are none (e.g. you're using just Tomcat 6), or you want to be independent from the container and/or framework, create a ServletContextListener with a ScheduledExecutorService. Further detail can be found in this answer.

Or when you're already on a Java EE 6 container which supports EJB 3.1 (JBoss AS 6, GlassFish 3, but thus not Tomcat 7), easiest is to create a @Singleton EJB with @Schedule method.

@Singleton
public class UpdateSubscriptions {

    @Schedule(hour="*/6", minute="0", second="0", persistent=false)
    public void run() {
        // Do your job here.
    }

}        

That's it. No further configuration is necessary.


Update: as per the comments, you're using Tomcat (6 or 7?). To start a thread during webapp's startup which runs the task every 6 hours, use the example as provided in the beforelinked answer and make the following change in the scheduleAtFixedRate() method

scheduler.scheduleAtFixedRate(new UpdateSubscriptions(), 0, 6, TimeUnit.HOURS);

The class UpdateSubscriptions must implement Runnable and the actual job needs to be done in the run() method which you @Override, like as in the example in the linked answer.