Java 定时任务:使用 JDBC 每 5 秒查询数据库最新数据
您可以使用 Java 的 ScheduledExecutorService 来创建定时器任务,然后使用 JDBC 连接到数据库并查询数据。以下是一个简单的示例代码:
import java.sql.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TimerTask {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
// Connect to the database
Connection conn = DriverManager.getConnection('jdbc:mysql://localhost:3306/mydatabase', 'root', 'password');
Statement stmt = conn.createStatement();
// Query data from the database
long currentTime = System.currentTimeMillis();
long startTime = currentTime - 5000;
String query = 'SELECT * FROM mytable WHERE timestamp BETWEEN ' + startTime + ' AND ' + currentTime + ' ORDER BY timestamp DESC LIMIT 5';
ResultSet rs = stmt.executeQuery(query);
// Process the query results
while (rs.next()) {
// Do something with each row of data
// For example:
int id = rs.getInt('id');
String name = rs.getString('name');
Timestamp timestamp = rs.getTimestamp('timestamp');
System.out.println(id + ' ' + name + ' ' + timestamp);
}
// Close the database connection
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}, 0, 5, TimeUnit.SECONDS);
}
}
这个示例代码使用 MySQL 数据库,所以您需要将连接字符串中的'mydatabase'替换为您的数据库名称,'root'替换为您的数据库用户名,'password'替换为您的数据库密码。此外,您还需要将'mytable'替换为您要查询的表名,并将'timestamp'替换为您的表中时间戳字段的名称。
在每个定时器任务中,我们首先获取当前时间戳,并计算出最近 5 秒的起始时间戳。然后我们使用这些起始和结束时间戳来构建查询字符串,并使用 JDBC 执行查询操作。最后,我们通过处理查询结果来处理每一行数据。在这个例子中,我们只是简单地打印每个行的 ID、名称和时间戳。您需要根据您的要求修改此代码以处理您的数据。
原文地址: https://www.cveoy.top/t/topic/mLwK 著作权归作者所有。请勿转载和采集!