TimerTask没有运行

时间:2014-04-02 07:28:20

标签: java multithreading timer 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){                
            }
        }        
    }

这是带有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 个答案:

答案 0 :(得分:0)

您:

  1. "处理"带空块的所有异常;
  2. 没有释放数据库资源的finally;
  3. 没有任何应该关闭数据库连接的代码行,即使是在快乐的一天"场景。
  4. 您的程序停止工作,因为每次运行任务时,都会挂起一个数据库连接。很快就没有更多的联系可以获得了,但是你没有得到通知,因为你决定不记录这个例外。