3
我想實現一個ScheduledExecutorService線程循環每秒,但現在它只有一次循環。ScheduledExecutorService只循環一次
我的問題是我如何設置它,使它週期性地循環而不是一次迭代?
另外,如何將連接池傳遞到線程,以便每次迭代都可以查詢數據庫?任何幫助深表感謝。
public static void main(String[] args) throws InterruptedException {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
AdminManager frame = new AdminManager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
BoneCP connectionPool = null;
Connection connection = null;
try {
// load the database driver (make sure this is in your classpath!)
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
// setup the connection pool
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://192.0.0.1:3306/database"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
config.setUsername("root");
config.setPassword("");
connectionPool = new BoneCP(config); // setup the connection pool
connection = connectionPool.getConnection(); // fetch a connection
if (connection != null){
System.out.println("Connection successful!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.schedule(new Runnable(){
@Override
public void run(){
System.out.println("Working ... ");
}
}, 1, TimeUnit.SECONDS);
//connectionPool.shutdown(); // shutdown connection pool.
}
好。感謝您向我展示scheduleAtFixed Rate方法。我試圖聲明連接最後,它給了我以下錯誤...線程「主」java.lang.Error中的異常:未解決的編譯問題: \t無法分配最終的局部變量連接。它必須是空白的並且不使用複合賦值 \t未處理的異常類型SQLException \t未處理的異常類型SQLException – scriptdiddy 2012-07-07 23:32:49
爲什麼?爲什麼在線程外部獲得Connection?只需在線程中獲取它,一個不錯的本地限制變量(連接不是線程安全的)。使ConnectionPool成爲final,然後使用它獲取線程內部的連接。 – MJB 2012-07-08 07:32:21
yea可能分配得更好。 – megakorre 2012-07-08 08:27:24