2013-07-12 59 views
0

我正在寫一個使用jsf的java ee應用程序。我定義了一些底色過程,如定期upating數據庫等。這裏是代碼:關閉項目後線程仍然退出,如何殺死它?

public class AppServletContextListener implements ServletContextListener{ 
    @Override 
public void contextInitialized(ServletContextEvent arg0) { 
    zamanli zm = new zamanli(); 
     try { 
      zm.programBasla(); 
     } catch (MalformedURLException ex) { 
      Logger.getLogger(AppServletContextListener.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (IOException ex) { 
      Logger.getLogger(AppServletContextListener.class.getName()).log(Level.SEVERE, null, ex); 
     } 
}  
} 

和類:

public class zamanli { 
    public void programBasla() throws MalformedURLException, IOException { 
    int delay = 5000; //5 sn sonra başlar 
    int period = 600000; //10 dkda tekrar 
    Timer timer = new Timer(); 
    TimerTask task = new TimerTask() { 
     @Override 
     public void run() { 

      Runtime r = Runtime.getRuntime(); 
      Process p = null; 

      try { 
       // p = r.exec("c:\\WINDOWS\\system32\\calc"); 
       System.out.println(Now()); 

      } catch (Exception e) { 

       System.out.println("Çalışmadı"); 
      } 
      try { 
       getCurrentExchangeValue(); 
      } catch (MalformedURLException ex) { 
       Logger.getLogger(zamanli.class.getName()).log(Level.SEVERE, null, ex); 
      } catch (IOException ex) { 
       Logger.getLogger(zamanli.class.getName()).log(Level.SEVERE, null, ex); 
      } 

     } 
    }; 

的問題是,程序完成後,即使我關閉項目,所以我的數據庫不斷更新。那麼,如何在程序關閉時殺死線程呢?

感謝

+1

不要在JEE環境中使用顯式線程。依靠提供的設施,請改爲:http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html –

+1

不好的主意!相關:http://stackoverflow.com/questions/7499534/applicationscope-bean-that-uses-a-timertask-sheduler-good-or-bad/7499769#7499769 – BalusC

回答

2

使用ScheduledExecutorService而不是Timer,並使用ThreadFactory其派生的daemon thread代替普通螺紋:

private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() 
{ 
    private final ThreadFactory factory = Executors.defaultThreadFactory(); 

    @Override 
    public Thread newThread(final Runnable r) 
    { 
     final Thread ret = factory.newThread(r); 
     ret.setDaemon(true); 
     return ret; 
    } 
}; 

// ... 
private final ScheduledExecutorService service 
    = Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY); 

//... 
service.scheduleAtFixedRate(etc etc); 

讓這個在service參考可供contextDestroyed(),那將是更容易;那麼你不必使用守護進程線程,只需在其中調用service.shutdownNow()即可。

2

據我所看到的,你要的方法添加到您的AppServletContextListener稱爲contextDestroyed(ServletContextEvent)。將zamanli對象存儲爲AppServletContextListener類的實例變量,並使用contextDestroyed方法停止zamanli

但總的來說,我會建議不要在Java EE環境中啓動自己的線程。