美文网首页
Spring动态创建定时任务

Spring动态创建定时任务

作者: 熊本猫 | 来源:发表于2021-06-10 19:29 被阅读0次

    创建config

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Bean;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
    import org.springframework.stereotype.Component;
    
    @Component
    @Slf4j
    public class RecordScheduleTask {
    
        @Bean
        public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
            log.info("----request threadPoolTaskScheduler, 创建定时任务调度线程池 !----");
            ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
            threadPoolTaskScheduler.setPoolSize(64); //线程池大小
            threadPoolTaskScheduler.setThreadNamePrefix("taskSchedulerExecutor-");
            threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
            threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
            return threadPoolTaskScheduler;
        }
    }
    

    插入定时任务

    ...
    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    
    private Map<Long, List<ScheduledFuture>> scheduledFutureMap = new ConcurrentHashMap<>();
    
    public void createScheduleTask(ScheduleRecordExeModel exeModel) {
            List<ScheduledFuture> futureList = new ArrayList<>();
    
            exeModel.getCronList().forEach(cron -> {
                ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(() -> {
                            executeRecordBySystem(exeModel.getRecordId());
                        },
                        (triggerContext) -> {
                            CronTrigger cronTrigger = new CronTrigger(cron);
                            return cronTrigger.nextExecutionTime(triggerContext);
                        });
                futureList.add(scheduledFuture);
            });
    
            if (!CollectionUtils.isEmpty(futureList)) {
                scheduledFutureMap.put(exeModel.getRecordId(), futureList); //存储定时任务的map,不是必须的
            }
        }
    

    服务启动时自动创建定时任务

     @PostConstruct //这个注解代表在服务启动的时候执行
        private void initScheduleTask(){
            List<xxx> scheduleRecords = xxx;
            scheduleRecords.forEach(record ->{
                ScheduleRecordExeModel exeModel = xxx;
                createScheduleTask(exeModel);
            });
        }
    

    相关文章

      网友评论

          本文标题:Spring动态创建定时任务

          本文链接:https://www.haomeiwen.com/subject/ohjpeltx.html