收集每个设备的数据按时间每秒记录,需要在间隔时间上减去消耗的时间得到真正间隔时间
synchronized (a) {
//获取系统时间作为基准时间
long timestamp = System.currentTimeMillis();
LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
Modbus4jUtils modbus = new Modbus4jUtils("127.0.0.1");
while (true) {
long start = System.currentTimeMillis();//记录消耗的开始时间
int[] offsetData = new int[] { 0x00 };
BatchResults<Number> batchHoldingRegister = modbus.batchHoldingRegister(1, 3, offsetData);
long end = System.currentTimeMillis();//消耗的结束时间
dateTime = dateTime.plusSeconds(1);//时间加一秒
// 将加一秒后的时间自定义格式输出
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.err.println(formattedDateTime);
try {
//间隔时间,为1秒减去消耗时间
a.wait(1000 - (end - start));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}