定时任务线程池的使用

4 阅读1分钟

 1、配置定时任务启动

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

2、具体使用

import org.springframework.scheduling.TaskScheduler;

@Component
public class TaskServiceImpl extends TaskService {

    // 预设的定时任务名称
    private final Map<String, ScheduledFuture<?>> scheduledJobs = new HashMap<>();

    @Resource
    private TaskScheduler taskScheduler;

    @Override
    public boolean startJob(String key, String croon) {
        log.info("================ ⏹️ 正在启动定时任务{} ================", key);
        try {
            // 校验cron表达式是否有效
            if(!CronExpression.isValidExpression(cron)){
                // todo cron表达式无效处理    
            }
                    
            // 取消已存在的任务
            this.cancelJob(key);

            // 创建新的定时任务
            CronTrigger cronTrigger = new CronTrigger(cron);
            Runnable jobTask = () -> {
                // todo 任务内容
            };
            ScheduledFuture<?> future = taskScheduler.schedule(jobTask, cronTrigger);
            scheduledJobs.put(node.getCode(), future);

            Date nextExecutionTime = cronTrigger.nextExecutionTime(new SimpleTriggerContext());
            log.info("✅ 定时任务 '{}' 已启动,cron表达式: {},下一次执行时间:{}", key, cron, DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", nextExecutionTime));
        } catch (Exception e) {
            log.error("❌ 启动定时任务 '{}' 失败", key);
            return false;
        }
        return true;
    }

    @Override
    public void cancelJob(String key) {
        ScheduledFuture<?> future = scheduledJobs.remove(key);
        if (future != null && !future.isCancelled()) {
            future.cancel(false);
            log.info("⏹️  定时任务 '{}' 已取消", nodeCode);
        }
    }

}

核心执行为

ScheduledFuture<?> future = taskScheduler.schedule(jobTask, cronTrigger);

TaskScheduler是spring自带的定时任务线程池,可以在指定时间(cron)将预设任务投入线程池中并行执行,该线程池默认线程数为4,应用于需要动态更改时间或者启用关闭的定时任务