package com.tongran.agentserver.scheduler; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; 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.util.concurrent.ScheduledFuture; @Component @EnableScheduling public class HeartScheduler { private ScheduledFuture scheduledTask; @Resource private TaskScheduler taskScheduler; @Resource private NettyTcpClient nettyTcpClient; @PostConstruct public void init() { // 等待5秒 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } startTask(30000); // 默认30秒间隔启动 } public void startTask(long intervalMillis) { if (scheduledTask != null) { scheduledTask.cancel(false); } Runnable task = () -> { // 业务逻辑 if (!nettyTcpClient.isConnected()) { try { nettyTcpClient.connect(); } catch (InterruptedException e) { e.printStackTrace(); } } // 发送心跳包 JSONObject object = new JSONObject(); object.put("strength","31"); String clientId = AgentUtil.getMotherboardUUID(); Message message = Message.builder().clientId(clientId).dataType("HEARTBEAT").data(object.toString()).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; } } }