Background timer task in JSP/Servlet web applicati

2019-01-02 18:24发布

This question already has an answer here:

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?

1条回答
明月照影归
2楼-- · 2019-01-02 18:58

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.

查看更多
登录 后发表回答