package com.tongran.agentserver.scheduler; import com.alibaba.fastjson2.JSON; import com.tongran.agentserver.server.collect.memory.MemoryService; import com.tongran.agentserver.server.collect.vo.MemoryVO; 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.concurrent.ScheduledFuture; @Component @EnableScheduling public class MemoryScheduler { @Resource private TaskScheduler taskScheduler; private ScheduledFuture scheduledTask; @Resource private NettyTcpClient nettyTcpClient; @Resource private MemoryService memoryService; @PostConstruct public void init() { // 等待47秒 try { Thread.sleep(47000); } 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()) { // 发送内存信息包 MemoryVO memoryVO = memoryService.query(); String data = JSON.toJSONString(memoryVO); String clientId = AgentUtil.getMotherboardUUID(); Message message = Message.builder().clientId(clientId).dataType("MEMORY").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; } } }