面试老哥问到这个问题。你们项目里有使用到定时任务,那定时任务多吗?有没有出现问题过
那肯定有,应该有个单独的定时任务模块,里面的定时任务有10来个呢,问题也出过,因为一般一个定时任务报错后,后面的任务就不执行了。卡住了。
解决方案:
- 尽量少让定时任务在同一时间执行,减少卡死几率,业务允许才行。
- 使用@Async注解实现异步任务 这种方式比较简单,在定时任务上加上@Async注解,注意:如果是SpringBoot项目需启动类配合加上 @EnableAsync才会生效
- 开启一个线程池,手动设置定时任务的线程池大小,像我们项目有10多个任务,那么开了10个,已经能避免单任务出现问题导致的后续任务不执行问题了
推荐使用线程池的方式,便于管理
/**
* @author bo bo
* @package: com.springboot.task.com.springboot.session.config
* @date: 2020/5/20 9:40
* @copyright: Copyright (c) 2020
* @version: V1.0
* @description: 定时任务配置,配置线程池,使用不同线程执行任务,提升效率
*/
@Configuration
@EnableScheduling
@ComponentScan(basePackages = {"com.springboot.task.job"})
public class TaskConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
/**
* 这里等同于配置文件配置
* {@code spring.task.scheduling.pool.size=20} - Maximum allowed number of threads.
* {@code spring.task.scheduling.thread-name-prefix=Job-Thread- } - Prefix to use for the names of newly created threads.
* {@link org.springframework.boot.autoconfigure.task.TaskSchedulingProperties}
*/
@Bean
public Executor taskExecutor() {
return new ScheduledThreadPoolExecutor(20, new BasicThreadFactory.Builder().namingPattern("Job-Thread-%d").build());
}
}
在指定文件夹下使用定时任务即可