SpringBoot2定时任务配置文件

4 阅读1分钟
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author sunlq
 * @version 1.0
 * @description: TODO
 * @date 2026/3/15 15:40
 */
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
    public static ConcurrentHashMap<String, ScheduledFuture> cache = new ConcurrentHashMap<>();

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 创建一个线程池调度器
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 设置线程池大小
        taskScheduler.setPoolSize(10);
        // 设置线程名前缀
        taskScheduler.setThreadNamePrefix("scheduled-task-pool-");
        // 设置等待任务完成再关闭线程池
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间(单位:秒)
        taskScheduler.setAwaitTerminationSeconds(60);
        taskScheduler.initialize();

        taskRegistrar.setTaskScheduler(taskScheduler);
    }
}
package com.yayangsoft.task;

//import com.yayangsoft.config.ScheduleConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Logger;

/**
 * @author sunlq
 * @version 1.0
 * @description: TODO
 * @date 2026/3/15 20:26
 */
@Slf4j
@Component
public class DynamicTask {
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    public void startCron() {
        getTasks().forEach(customizeTask -> {
            ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(customizeTask, new CronTrigger(customizeTask.getCron()));
            ScheduleConfig.cache.put(customizeTask.getName(), scheduledFuture);
        });
    }
    public void stop(String taskId) {
        if (ScheduleConfig.cache.isEmpty()) return;
        ScheduledFuture scheduledFuture = ScheduleConfig.cache.get(taskId);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            ScheduleConfig.cache.remove(taskId);
        }
    }
    public void stopAll() {
        if (ScheduleConfig.cache.isEmpty()) return;
        ScheduleConfig.cache.values().forEach(scheduledFuture -> scheduledFuture.cancel(true));
    }
    private List<CustomizeTask> getTasks() {
        return Arrays.asList(new CustomizeTask("任务一", "0/2 * * * * ?"), new CustomizeTask("任务二", "0/3 * * * * ?"));
    }
    private class CustomizeTask implements Runnable {
        private String name;
        private String cron;
        CustomizeTask(String name, String cron) {
            this.name = name;
            this.cron = cron;
        }
        public String getCron() {
            return this.cron;
        }
        public String getName() {
            return this.name;
        }
        @Override
        public void run() {
            log.info("当前任务名称:{}", name);
        }
    }
}
package com.yayangsoft.controller;

import com.yayangsoft.task.DynamicTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sunlq
 * @version 1.0
 * @description: TODO
 * @date 2026/3/15 20:30
 */

@RestController
public class TaskTestController {
    @Autowired
    private DynamicTask task;

    @RequestMapping("start")
    public void startTask() {
        task.startCron();
    }

    @RequestMapping("stopById")
    public void stopById(String taskId) {
        task.stop(taskId);
    }

    @RequestMapping("stopAll")
    public void stopAll() {
        task.stopAll();
    }
}