创建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);
});
}