例如定时任务方法上的注解 cron表达式是这样会的:
@Async //异步
@Scheduled(cron = "0 59 * * * ?") //表达式 每小时的59分执行一次
@DataSource(DataSourceType.YK) //自定义注解切库
出现的问题: 插入数据库的时间对应不上:
是因为springboot默认给定时任务配置的线程池只有一个线程,当很多个定时任务都加了异步注解,没有配置线程池时,他们会因为只有一个线程出问题。
因为springboot的定时任务默认的线程池只有一个线程,就算加了异步,也不能使得一个任务结束下个任务才能开始,所以要配置一下或者重写定时任务的线程池,也可以将异步注解去掉,将异步注解去掉,springboot就会给定时任务配置一个固定的线程,不受干扰.
没有配置定时任务线程池时,默认用的是springboot分配给定时任务的线程池SimpleAsyncTaskExecutor,当一个服务定时任务过多时,会有问题比如你一个任务的周期是5秒,这5秒你要发送100条短信,用之前的固定的线程肯定没有问题,现在你改成多个线程。5秒如果你上个任务没有执行完成,那现在你任务的第二个周期到了还是会执行,如果没有控制可能会重复发
配置定时任务:
1、启动类
添加@EnableScheduling开启对定时任务的支持,@EnableAsync开启异步注解
2、编写定时任务类
@Component
@Slf4j
public class SaveDeviceRunTime
@Async
@Scheduled(cron = "0 59 * * * ?")
public void SaveDeviceRunTime()
复制代码
添加@Async注解,表示该定时任务是异步执行的,因为上面线程池配置了名字,所以可以看到打印的日志是该线程池中的线程在执行任务,如果没有配置线程池的话会默认使用SimpleAsyncTaskExecutor,这个异步执行器每次都会开启一个子线程执行,性能消耗比较大,所以最好是自己配置线程池
如果没有配置异步注解的花,springboot就会分配固定的线程scheduling
所以可以在启动类上配置线程池或者建一个线程池配置类
复制代码
@Bean
public Executor executor1() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("test-schedule1-");
executor.setMaxPoolSize(20);
executor.setCorePoolSize(15);
executor.setQueueCapacity(10);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
复制代码
or:
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean
public Executor executor1() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("test-schedule1-");
executor.setMaxPoolSize(20);
executor.setCorePoolSize(15);
executor.setQueueCapacity(10);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
@Bean
public Executor executor2() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("test-schedule2-");
executor.setMaxPoolSize(20);
executor.setCorePoolSize(15);
executor.setQueueCapacity(10);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
测试如下:
@Component
@Slf4j
@EnableScheduling
public class test {
@Async("executor1") //指定线程池bean的名字 为什么是这个名字,可以自行学习下spring 关于bean的生命周期和创建过程
@Scheduled(cron = "0 0/1 * * * ?")
public void test() {
System.out.println(Thread.currentThread().getName());
}
}
复制代码
复制代码
@Component
@Slf4j
@EnableScheduling
public class test1 {
@Async
@Scheduled(cron = "0 0/1 * * * ?")
public void test1() {
System.out.println(Thread.currentThread().getName() + "-------");
}
}
复制代码
结果: 可以看到未指定线程池,默认就会使用的是SimpleAsyncTaskExecutor
也可以选择不配置异步,用同步,那么springboot就会给它分配固定的线程,不会被干扰
博客园链接: 定时任务cron表达式时间失效问题(未按表达式时间运行) 配置定时任务线程池或者同步解决 – 古家杰 – 博客园 (cnblogs.com)