21

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?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
MalTec
  • 1,290
  • 2
  • 13
  • 30

1 Answers1

40

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.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • 2
    +1 can't get an answer any perfect than this. – asgs Mar 18 '11 at 21:17
  • I am using Tomcat only. I saw the linked answer too. 1. I intended to use it in a class, was crntlt not going to use JSP. But, is servlet a better way? 2. if i put it in a servlet as shown in linked answer won't it create new thread every 6 hours? – MalTec Mar 19 '11 at 12:20
  • It's not a servlet. It's a listener. And there's only one instance of it in webapp's lifetime (the same applies to servlets by the way). – BalusC Mar 19 '11 at 13:10
  • I imagine that you've possibly a hard time in setting the `scheduleAtFixedRate()` method. I've updated the answer with an example which runs the `UpdateSubscriptions` instance every 6 hours. – BalusC Mar 19 '11 at 16:59
  • By using the EB scheduler, you'll be limited to the restrictions of EJBs. Hence, if you need to use something like a multithreaded HttpClient, you shouldn't do it using an EJB timer as it may cause the threads to get screwed up. – Allan Lykke Christensen Apr 14 '11 at 09:13