2010-06-17 18 views
7

我需要在我的web應用程序(jsp on tomcat)中執行定期操作(調用java方法)。 我該怎麼做? Java守護進程或其他解決方案?我如何製作Java Daemon

+0

類似的帖子http://stackoverflow.com/questions/3053936/how-to-execute-task-for-a-specific-period-in-java/3053971#3053971 – 2010-06-17 15:11:07

回答

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); 
    } 
} 
+0

我的操作沒有結束時間。 我需要這樣做,例如,每週。 我該怎麼做? – enfix 2010-06-17 14:49:18

+0

如果您使用ScheduledExecutorService,則需要使用scheduleWithFixedDelay或scheduleAtFixedRate。對於每週運行一次的任務,或者在每月的某些時候,我傾向於支持Quartz,因爲您可以在配置中提供一個簡單的cron表達式來描述作業應該運行的確切時間。 – Adamski 2010-06-17 14:56:33

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> 

只是更多的精神食糧!