我正在寫一個使用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);
}
}
};
的問題是,程序完成後,即使我關閉項目,所以我的數據庫不斷更新。那麼,如何在程序關閉時殺死線程呢?
感謝
不要在JEE環境中使用顯式線程。依靠提供的設施,請改爲:http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html –
不好的主意!相關:http://stackoverflow.com/questions/7499534/applicationscope-bean-that-uses-a-timertask-sheduler-good-or-bad/7499769#7499769 – BalusC