Springboot 定时任务 定时执行 定时关闭 配置文件实时配置

Springboot 定时任务 定时执行 定时关闭  配置文件实时配置

核心配置类

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.Instant;
import java.time.LocalTime;
import java.util.TimeZone;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 定时开启 停止任务调度
 */
@Slf4j
@Component
@RefreshScope
public class DynamicTaskScheduler {

    private final int FREQUENT = 300;

    private final TaskScheduler taskScheduler;
    private final AssignSalesConfig assignSalesConfig;
    private final TelephoneCallerBindRecordScheduler telephoneCallerBindRecordScheduler;

    private final AtomicReference<ScheduledFuture<?>> startFuture = new AtomicReference<>();
    private final AtomicReference<ScheduledFuture<?>> stopFuture = new AtomicReference<>();
    private volatile ScheduledFuture<?> taskFuture;
    private final AtomicBoolean taskRunning = new AtomicBoolean(false);

    public DynamicTaskScheduler(TaskScheduler taskScheduler,
                                AssignSalesConfig assignSalesConfig, TelephoneCallerBindRecordScheduler telephoneCallerBindRecordScheduler) {
        this.taskScheduler = taskScheduler;
        this.assignSalesConfig = assignSalesConfig;
        this.telephoneCallerBindRecordScheduler = telephoneCallerBindRecordScheduler;
    }

    /**
     * 初始化注册
     */
    @PostConstruct
    public void init() {
        scheduleControlTasks();
    }

    /**
     * 监听配置刷新事件
     */
    @EventListener
    public void onRefreshEvent(org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent event) {
        log.info("Config refreshed, rescheduling tasks...");
        rescheduleTasks();
    }

    /**
     * 重置调度
     */
    private synchronized void rescheduleTasks() {
        cancelExistingControlTasks();
        scheduleControlTasks();
        checkAndAdjustTaskState();
    }

    /**
     * 调度初始化
     */
    private void scheduleControlTasks() {
        TimeZone timeZone = TimeZone.getDefault();

        startFuture.set(taskScheduler.schedule(this::startTask,
                new CronTrigger(assignSalesConfig.getStart(), timeZone)));

        stopFuture.set(taskScheduler.schedule(this::stopTask,
                new CronTrigger(assignSalesConfig.getStop(), timeZone)));

        log.info("Scheduled tasks - Start: {}, Stop: {}", assignSalesConfig.getStart(), assignSalesConfig.getStop());
    }

    /**
     * 获取任务状态
     */
    private void checkAndAdjustTaskState() {
        // 这里可以添加更复杂的逻辑来判断当前是否应该运行任务
        log.info("Current task state - running: {}", taskRunning.get());
    }

    /**
     * 取消存在的任务
     */
    private void cancelExistingControlTasks() {
        ScheduledFuture<?> start = startFuture.getAndSet(null);
        ScheduledFuture<?> stop = stopFuture.getAndSet(null);

        if (start != null && !start.isCancelled()) {
            start.cancel(false);
        }
        if (stop != null && !stop.isCancelled()) {
            stop.cancel(false);
        }
    }

    /**
     * 清理任务
     */
    @PreDestroy
    public void cleanup() {
        cancelExistingControlTasks();
        stopTask();
    }

    /**
     * 启动任务
     */
    private synchronized void startTask() {
        if (!taskRunning.get()) {
            taskFuture = taskScheduler.scheduleAtFixedRate(this::executeTask,
                    Instant.now(),
                    java.time.Duration.ofSeconds(FREQUENT));
            taskRunning.set(true);
            log.info("Task started at {}", LocalTime.now());
        }
    }

    /**
     * 结束任务
     */
    private synchronized void stopTask() {
        if (taskRunning.getAndSet(false)) {
            if (taskFuture != null && !taskFuture.isCancelled()) {
                taskFuture.cancel(false);
                log.info("Task stopped at {}", LocalTime.now());
            }
        }
    }

    /**
     * 任务调度
     */
    private void executeTask() {
        if (!taskRunning.get()) {
            return;
        }

        try {
            // 执行业务逻辑,可以使用assignSalesConfig中的配置
            telephoneCallerBindRecordScheduler.handle();
        } catch (Exception e) {
            log.error("Task execution failed: {}", e.getMessage());
        }
    }
}

 

定时配置类

@Getter
@Setter
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "assign")
public class AssignSalesConfig {

    private String start = "0 0 9 * * ?";

    private String stop = "0 0 18 * * ?";
}

 

业务处理类

@Slf4j
@Component
public class TelephoneCallerBindRecordScheduler {

    @Resource
    private TelephoneCalleeManager telephoneCalleeManager;
    /**
     * 定时 循环执行调度
     */
    public void handle() {
      // *** 业务处理
    }
}    

 

结束

posted @ 2025-08-04 15:17  ジ绯色月下ぎ  阅读(6)  评论(0)    收藏  举报