高速设备状态
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

55 lines
1.9 KiB

package com.example.device.controller;
import com.example.device.entity.Device;
import com.example.device.entity.Status;
import com.example.device.service.DeviceService;
import com.example.device.service.StatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.List;
@Component
@EnableScheduling
public class DeviceStatus {
@Autowired
private DeviceService deviceService;
@Autowired
private StatusService statusService;
//每天凌晨开始执行,每4小时执行一次
@Scheduled(cron = "0 0 4/0 * * ?")
public void generateDeviceStatus(){
deviceStatus();
}
public void deviceStatus() {
Status status=new Status();
List<Device> deviceList = deviceService.SelectList();
for (Device device : deviceList) {
try {
InetAddress address = InetAddress.getByName(device.getDeviceIp());
boolean reachable = address.isReachable(5000); // Timeout: 5 seconds
status.setDeviceNo(device.getDeviceNo());
status.setDeviceName(device.getDeviceName());
LocalDateTime localDateTime = LocalDateTime.now();
status.setTime(localDateTime);
//1-在线 0-离线
if (reachable) {
status.setDeviceStatus(1);
} else {
status.setDeviceStatus(0);
}
statusService.Add(status);
} catch (IOException e) {
System.out.println("Error pinging " + device.getDeviceIp() + ": " + e.getMessage());
}
}
}
}