我如何制作Java守护进程

我需要在我的web应用程序(tomcat上的jsp)中进行定期操作(调用java方法)。 我怎样才能做到这一点 ? Java守护程序或其他解决方案?

您可以使用ScheduledExecutorService定期执行任务。 但是,如果您需要更复杂的类似cron的调度,那么请查看Quartz 。 特别是如果沿着这条路线,我建议将Quartz与Spring结合使用 ,因为它提供了更好的API并允许您在配置中控制作业。

ScheduledExecutorService示例(取自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); } } 

亚当斯的回答是正确的。 如果你最终滚动自己(而不是去石英路线),你会想要在ServletContextListener中解决问题 。 这是一个使用java.util.Timer的例子,它或多或少是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 ); } } 

然后,这将在您的web.xml中

  com.TimerTaskServletContextListener  

更多值得思考的东西!