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.beans.factory.annotation.Value; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import javax.annotation.Resource; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.util.concurrent.ScheduledFuture; @Component @EnableScheduling public class HeartScheduler { private final TaskScheduler taskScheduler; private ScheduledFuture currentTask; private final Object lock = new Object(); @Value("${task.initial.delay:5000}") private long initialDelay; @Value("${task.interval:30000}") private long interval; @Resource private NettyTcpClient nettyTcpClient; public HeartScheduler(TaskScheduler taskScheduler) { this.taskScheduler = taskScheduler; } @EventListener(ApplicationReadyEvent.class) public void startDynamicTask() { AssertLog.info("启动心跳定时任务 - 延迟: {}ms, 间隔: {}ms", initialDelay, interval); scheduleTask(initialDelay, interval); } public void scheduleTask(long delayMillis, long intervalMillis) { synchronized (lock) { // 取消现有任务 if (currentTask != null) { currentTask.cancel(false); } // 安排新任务 currentTask = taskScheduler.scheduleWithFixedDelay( this::dynamicPeriodicTask, Instant.now().plusMillis(delayMillis), Duration.ofMillis(intervalMillis) ); } } public void dynamicPeriodicTask() { AssertLog.info("心跳定时任务执行 - 时间: {}", LocalDateTime.now()); performDynamicTask(); } private void performDynamicTask() { // 判定客户端与服务端是否连接 if (!nettyTcpClient.isConnected()) { try { nettyTcpClient.connect(); // 等待10秒 try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } 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); } public void updateSchedule(long newDelay, long newInterval) { AssertLog.info("更新调度配置 - 延迟: {}ms, 间隔: {}ms", newDelay, newInterval); scheduleTask(newDelay, newInterval); } @PreDestroy public void cleanup() { if (currentTask != null) { currentTask.cancel(false); } } }