Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i make a Java Daemon

Tags:

java

jsp

tomcat

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 ?

like image 340
enfix Avatar asked Jun 17 '10 14:06

enfix


2 Answers

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);
    }
 }
like image 86
Adamski Avatar answered Oct 04 '22 05:10

Adamski


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!

like image 45
Greg Case Avatar answered Oct 04 '22 05:10

Greg Case