Java 定时任务:每隔 5 秒从数据库查询数据
可以使用 Java 中的 Timer 和 TimerTask 类来实现定时器任务,使用 JDBC 来连接数据库并查询数据。具体实现步骤如下:
-
创建 Timer 对象和 TimerTask 对象,重写 TimerTask 类的 run() 方法,在 run() 方法中编写数据库查询的代码。
-
使用 JDBC 连接数据库,并编写查询 SQL 语句,设置查询条件为当前时间前 5 秒内的数据。
-
在 Timer 对象上调用 schedule() 方法,设置定时器任务的执行时间间隔为 5 秒。
下面是示例代码:
import java.sql.*;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTaskExample {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection('jdbc:mysql://localhost:3306/test', 'root', '123456');
// 编写查询 SQL 语句
String sql = 'SELECT * FROM test_table WHERE create_time >= DATE_SUB(NOW(), INTERVAL 5 SECOND)';
pstmt = conn.prepareStatement(sql);
// 执行查询
rs = pstmt.executeQuery();
// 处理查询结果
while (rs.next()) {
System.out.println(rs.getInt('id') + ' ' + rs.getString('name') + ' ' + rs.getTimestamp('create_time'));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
};
// 设置定时器任务的执行时间间隔为 5 秒
timer.schedule(task, 0, 5000);
}
}
最佳实践:
- 使用 try-with-resources 语句来简化资源管理,自动关闭连接和语句。
- 在数据库连接池中创建连接,以提高性能。
- 考虑使用日志记录来跟踪任务执行和错误。
- 使用线程池来管理定时任务,防止过多线程占用资源。
- 定期检查和维护定时任务,确保其正常运行。
通过以上步骤和最佳实践,您可以轻松创建 Java 定时任务,定期从数据库中查询数据。
原文地址: https://www.cveoy.top/t/topic/mLtg 著作权归作者所有。请勿转载和采集!