2014-04-02 109 views
0

我正在構建一個應用程序,每分鐘查詢一次數據庫。我使用TimerTask類來查詢數據庫。該方法工作了一段時間,並完全停止。我該怎麼辦?這裏的下面TimerTask沒有運行

public class DateMgr extends TimerTask{ 
     static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
     static final String DB_URL = "jdbc:mysql://localhost:3306/reminder"; 
     static final String USER = "username"; 
     static final String PASS = "password"; 
     @Override 
     public void run(){ 
      Statement stmt = null; 
      Connection conn = null; 

      try{ 

       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); 
       //get current date time with Date() 
       Date d = new Date(); 

       String m = dateFormat.format(d); 
       String s = m + ":00.0"; 
       System.out.println(dateFormat.format(s)); 
       //STEP 2: Register JDBC driver 
       Class.forName("com.mysql.jdbc.Driver"); 

       //STEP 3: Open a connection 
       System.out.println("Connecting to a selected database..."); 
       conn = DriverManager.getConnection(DB_URL, USER, PASS); 
       System.out.println("Connected database successfully..."); 

       //STEP 4: Execute a query 
       System.out.println("Creating statement..."); 

       stmt = conn.createStatement(); 
       String sql = "SELECT * FROM reminder.list"; 
       ResultSet rs = stmt.executeQuery(sql); 
       //STEP 5: Extract data from result set 
       while(rs.next()){ 
        //Retrieve by column name 
        int id = rs.getInt("id"); 
        String message = rs.getString("Message"); 
        String when = rs.getString("When");            
        System.out.println("Time for " + message + " At " + when); 
       } 
       rs.close();           
      }catch (Exception e){     
      } 
     }   
    } 

的代碼,這是Timer類與main()方法

public class Reminder { 
    Timer timer; 

    public Reminder(int seconds) { 
     timer = new Timer(); 
     timer.schedule(new DateMgr(), 0, seconds*1000); 
    } 
    public static void main (String args[]){ 
     new Reminder(20); 
    }   
} 
+0

你吞下'Exception'(因此所有未經檢查的異常,包括NPE)並且什麼也不做?至少在某處打印堆棧跟蹤;沒有這些,沒有診斷是可能的 – fge

回答

0

您:

  1. 「處理」 與空塊所有的異常;
  2. 沒有finally您釋放數據庫資源的位置;
  3. 即使在「愉快的一天」的情況下也沒有任何應該關閉數據庫連接的代碼行。

程序停止工作,因爲每次任務運行時,都會掛起一個數據庫連接。很快,沒有更多的連接要獲得,但是你不知道這個,因爲你決定不記錄這個異常。