How can I do Java Daemon

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

+7
java jsp tomcat
source share
2 answers

You can use the ScheduledExecutorService to run the task periodically. However, if you need more complex cron-like planning, take a look at Quartz . In particular, I recommend using Quartz in combination with Spring if you go down this route, as it provides a more convenient API and allows you to control the launch of your work in the 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); } } 
+8
source share

Adams answers correctly for money. If you end up rolling on your own (rather than walking the quartz path), you want to kick things into the ServletContextListener . Here's an example using java.util.Timer, which is a more or less dumb version of 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 this happens in your web.xml

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

Just more food for thought!

+4
source share

All Articles