81 lines
2.6 KiB
Java
81 lines
2.6 KiB
Java
|
|
package com.tongran.agentserver.scheduler;
|
||
|
|
|
||
|
|
import com.alibaba.fastjson2.JSON;
|
||
|
|
import com.alibaba.fastjson2.JSONArray;
|
||
|
|
import com.tongran.agentserver.server.collect.disk.DiskService;
|
||
|
|
import com.tongran.agentserver.server.collect.vo.DiskVO;
|
||
|
|
import com.tongran.agentserver.server.netty.NettyTcpClient;
|
||
|
|
import com.tongran.agentserver.server.netty.model.Message;
|
||
|
|
import com.tongran.agentserver.utils.AgentUtil;
|
||
|
|
import com.tongran.agentserver.utils.AssertLog;
|
||
|
|
import org.springframework.scheduling.TaskScheduler;
|
||
|
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||
|
|
import org.springframework.stereotype.Component;
|
||
|
|
|
||
|
|
import javax.annotation.PostConstruct;
|
||
|
|
import javax.annotation.Resource;
|
||
|
|
import java.time.LocalDateTime;
|
||
|
|
import java.util.List;
|
||
|
|
import java.util.concurrent.ScheduledFuture;
|
||
|
|
|
||
|
|
@Component
|
||
|
|
@EnableScheduling
|
||
|
|
public class DiskScheduler {
|
||
|
|
|
||
|
|
@Resource
|
||
|
|
private TaskScheduler taskScheduler;
|
||
|
|
|
||
|
|
private ScheduledFuture<?> scheduledTask;
|
||
|
|
|
||
|
|
@Resource
|
||
|
|
private NettyTcpClient nettyTcpClient;
|
||
|
|
|
||
|
|
@Resource
|
||
|
|
private DiskService diskService;
|
||
|
|
|
||
|
|
@PostConstruct
|
||
|
|
public void init() {
|
||
|
|
// 等待27秒
|
||
|
|
try {
|
||
|
|
Thread.sleep(27000);
|
||
|
|
} catch (InterruptedException e) {
|
||
|
|
e.printStackTrace();
|
||
|
|
}
|
||
|
|
startTask(300000); // 默认300秒间隔启动
|
||
|
|
}
|
||
|
|
|
||
|
|
public void startTask(long intervalMillis) {
|
||
|
|
if (scheduledTask != null) {
|
||
|
|
scheduledTask.cancel(false);
|
||
|
|
}
|
||
|
|
|
||
|
|
Runnable task = () -> {
|
||
|
|
AssertLog.info("磁盘信息包准备={}", LocalDateTime.now());
|
||
|
|
// 业务逻辑
|
||
|
|
if (nettyTcpClient.isConnected()) {
|
||
|
|
// 发送磁盘信息包
|
||
|
|
List<DiskVO> list = diskService.queryDiskList();
|
||
|
|
String data = JSONArray.toJSONString(list);
|
||
|
|
String clientId = AgentUtil.getMotherboardUUID();
|
||
|
|
Message message = Message.builder().clientId(clientId).dataType("DISK").data(data).build();
|
||
|
|
// 将对象转为 JSON 字符串
|
||
|
|
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
|
||
|
|
AssertLog.info("发送磁盘信息包={}",json);
|
||
|
|
nettyTcpClient.sendMessage(json);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
scheduledTask = taskScheduler.scheduleAtFixedRate(task, intervalMillis);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void updateInterval(long newIntervalMillis) {
|
||
|
|
startTask(newIntervalMillis);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void stopTask() {
|
||
|
|
if (scheduledTask != null) {
|
||
|
|
scheduledTask.cancel(false);
|
||
|
|
scheduledTask = null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|