tags:

views:

148

answers:

2

I need to do a periodic operation (call a java method) in my web app (jsp on tomcat). How can i do this ? Java daemon or others solutions ?

+7  A: 

You could use a ScheduledExecutorService for periodic execution of a task. However, if you require more complex cron-like scheduling then take a look at Quartz. In particular I'd recommend using Quartz in conjunction with Spring if you go down this route, as it provides a nicer API and allows you to control your job firing in configuration.

ScheduledExecutorService Example (taken from Javadoc)

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }
Adamski
My operation don't have an end time.I need to do this, for example, every week.How can i do this ?
enfix
If you are using ScheduledExecutorService you need to use scheduleWithFixedDelay or scheduleAtFixedRate. For tasks running once per week or at certain times of the month I tend to favour Quartz, as you can provide a simply cron expression in config describing the exact times the job should run.
Adamski
+2  A: 

Adams answer is right on the money. If you do end up rolling your own (rather than going the quartz route), you'll want to kick things off in a ServletContextListener. Here's an example, using java.util.Timer, which is more or less a dumb version of the ScheduledExexutorPool.

public class TimerTaskServletContextListener implements ServletContextListener
{
   private Timer timer;

   public void contextDestroyed( ServletContextEvent sce )
   {
      if (timer != null) {
         timer.cancel();
      }
   }

   public void contextInitialized( ServletContextEvent sce )
   {
      Timer timer = new Timer();
       TimerTask myTask = new TimerTask() {
         @Override
         public void run()
         {
            System.out.println("I'm doing awesome stuff right now.");
         }
      };

      long delay = 0;
      long period = 10 * 1000; // 10 seconds;
      timer.schedule( myTask, delay, period );
  }

}

And then this goes in your web.xml

<listener>
   <listener-class>com.TimerTaskServletContextListener</listener-class>
 </listener>   

Just more food for thought!

gregcase