一、新建配置类,配置TaskScheduler
@Configuration public class ThreadAConfigurer { @Bean("taskScheduler") public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setThreadNamePrefix("autoTask"); taskScheduler.setPoolSize(10); return taskScheduler; } }
二、配置定时任务
由于Thread的内注入service为空,所以以参数形式传入到AutoSpThread类 ,taskRegistrar.addCronTask() 第二个参数配置定时启动任务的日期
@Component @Configuration public class AutoSpTask implements SchedulingConfigurer { @Autowired GlobalServiceConfig globalServiceConfig; @Autowired AutoSpService autoSpService; @Autowired TaskScheduler taskScheduler; private static final Logger LOG = LoggerFactory.getLogger(AutoSplitTask.class); @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setTaskScheduler(taskScheduler); String tPath = globalServiceConfig.getTiPath(); String dateStr = DateUtils.formatDate(new Date()); LOG.info("扫描定时任务"); taskRegistrar.addCronTask( new AutoSpThread(autoSplitService, dateStr, tPath), globalServiceConfig.getAutoSTaskCron()); } }