如何用java代码定时器任务用jdbc来每隔5秒从数据库中查询前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);
}
}
原文地址: https://www.cveoy.top/t/topic/bjnf 著作权归作者所有。请勿转载和采集!