java定时执行存储过程
时间: 2023-11-20 09:57:06 浏览: 131
JAVA定时执行
以下是Java定时执行存储过程的示例代码:
```java
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledTask {
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "123456";
private static final String CALL_PROCEDURE_SQL = "{call procedure_name()}";
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> {
Connection conn = null;
CallableStatement stmt = null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
stmt = conn.prepareCall(CALL_PROCEDURE_SQL);
stmt.execute();
} catch (SQLException e) {
// 处理异常
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// 处理异常
}
}
}, 0, 1, TimeUnit.HOURS);
}
}
```
该示例代码使用了Java的ScheduledExecutorService类来定时执行存储过程。在main方法中,我们创建了一个ScheduledExecutorService实例,并使用scheduleAtFixedRate方法来定时执行一个Runnable任务。在该任务中,我们获取数据库连接,准备调用存储过程的CallableStatement对象,并执行该对象的execute方法来执行存储过程。最后,我们在finally块中关闭了CallableStatement和Connection对象。
阅读全文