我如何制作Java守护进程

时间:2010-06-17 14:33:57

标签: java jsp tomcat

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

2 个答案:

答案 0 :(得分:8)

您可以使用ScheduledExecutorService定期执行任务。但是,如果您需要更复杂的类似cron的调度,请查看Quartz。特别是如果沿着这条路线走,我建议使用Quartz in conjunction with 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);
    }
 }

答案 1 :(得分:4)

亚当斯的回答是正确的。如果你最终滚动自己(而不是走石英路线),你会想要在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

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

更多值得思考的事情!

相关问题