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.PointVO; 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 PointScheduler { @Resource private TaskScheduler taskScheduler; private ScheduledFuture scheduledTask; @Resource private NettyTcpClient nettyTcpClient; @Resource private DiskService diskService; @PostConstruct public void init() { // 等待97秒 try { Thread.sleep(97000); } 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 list = diskService.queryPointList(); String data = JSONArray.toJSONString(list); String clientId = AgentUtil.getMotherboardUUID(); Message message = Message.builder().clientId(clientId).dataType("POINT").data(data).build(); // 将对象转为 JSON 字符串 String json = JSON.toJSONString(message); 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; } } }