package com.tongran.agentserver.scheduler; import com.alibaba.fastjson2.JSON; import com.tongran.agentserver.server.collect.cpu.CpuService; import com.tongran.agentserver.server.collect.vo.CpuVO; 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 CpuScheduler { @Resource private TaskScheduler taskScheduler; private ScheduledFuture scheduledTask; @Resource private NettyTcpClient nettyTcpClient; @Resource private CpuService cpuService; @PostConstruct public void init() { // 等待12秒 try { Thread.sleep(12000); } catch (InterruptedException e) { e.printStackTrace(); } startTask(300000); // 默认3分钟间隔启动 } public void startTask(long intervalMillis) { if (scheduledTask != null) { scheduledTask.cancel(false); } Runnable task = () -> { AssertLog.info("CPU信息包准备={}", LocalDateTime.now()); // 业务逻辑 if (nettyTcpClient.isConnected()) { // 发送CPU信息包 CpuVO cpuVO =cpuService.query(); String data = JSON.toJSONString(cpuVO); String clientId = AgentUtil.getMotherboardUUID(); Message message = Message.builder().clientId(clientId).dataType("CPU").data(data).build(); // 将对象转为 JSON 字符串 String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran"; AssertLog.info("发送CPU信息包={}",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; } } }