配置类:
/**
* 定时任务线程配置
*
*/
@Configuration
public class SchedulerConfig implements SchedulingConfigurer { @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 设置定时任务并发数目
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(100));
} }
定时任务执行方式:
单线程(串行)
多线程(并行)
并行任务和异步任务的配置:
SchedulingConfigurer: 将线程池注入TaskScheduler,并与ScheduledTaskRegistrar 关联;
AsyncConfigurer:用于异步处理
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer, AsyncConfigurer
{ /*
* 并行任务
*/
public void configureTasks(ScheduledTaskRegistrar taskRegistrar)
{
TaskScheduler taskScheduler = taskScheduler();
taskRegistrar.setTaskScheduler(taskScheduler);
} /**
* 并行任务使用策略:多线程处理(配置线程数等)
*
* @return ThreadPoolTaskScheduler 线程池
*/
@Bean(destroyMethod = "shutdown")
public ThreadPoolTaskScheduler taskScheduler()
{
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);
scheduler.setThreadNamePrefix("task-"); //设置线程名开头
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
} /*
* 异步任务
*/
public Executor getAsyncExecutor()
{
Executor executor = taskScheduler();
return executor;
} /*
* 异步任务 异常处理
*/
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
{
return new SimpleAsyncUncaughtExceptionHandler();
}
}