簡體   English   中英

TimerTask未運行

[英]TimerTask not running

我正在構建一個應用程序,該應用程序每分鍾都會查詢一次數據庫。 我使用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){                
            }
        }        
    }

這是帶有main()方法的Timer類

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

您:

  1. 用空塊“處理”所有異常;
  2. finally沒有釋放數據庫資源的位置;
  3. 沒有任何代碼行可以關閉數據庫連接,即使在“歡樂的日子”情況下也是如此。

您的程序停止工作,因為每次任務運行時,都會掛起一個數據庫連接。 很快,沒有更多的連接可以獲取,但是您沒有決定這樣做,因為您決定不記錄該異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM