1.实现SchedulingConfigurer接口,重写方法
@Configuration public class ScheduleConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar registrar) { registrar.setScheduler(Executors.newScheduledThreadPool(10)); } }
定时任务的方法依旧按照单线程的配置即可:
@PostConstruct @Scheduled(cron = "0/4 * * * * ?") public void testMultithreadingTaskByOverrideConfigureTasks() { logger.info("线程名字:{}",Thread.currentThread().getName()); }
2.添加task配置
@Configuration @EnableAsync public class AsyncConfig { private final int corePoolSize = 10; private final int maxPoolSize = 20; private final int queueCapacity = 10; @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.initialize(); return executor; } }
定时任务需要在原来单线程的基础上增加 @Async 注解:
@PostConstruct @Scheduled(cron = "0/4 * * * * ?") @Async public void testMultithreadingTaskByAddTaskConfig() { logger.info("线程名字:{}",Thread.currentThread().getName()); }
注:两种方法均测试通过,并且实现定时任务需要在启动类中增加 @EnableScheduling 注解