@Scheduled实现定时任务
使用@Scheduled注解需要springboot启动类上添加注解@EnableScheduling
@SpringBootApplication
@MapperScan(basePackages = {"com.xxx.*.mapper"})
@EnableScheduling
public class PictureProcessingAdminApplication{
public static void main(String[] args) {
SpringApplication.run(PictureProcessingAdminApplication.class, args);
}
}
同个任务的同步执行
同步执行:等待上一次定时任务结束后才开始cron表达式时间匹配
注意:同步任务所在类必须被spring扫描所管理才行,所以需要添加@Component注解。
很多人明明在方法在添加了@Scheduled注解,但是不生效都是这个原因,定时任务所在类没有被spring管理。
@Component
public class taskTest {
@Scheduled(cron = "0 */1 * * * ?")
public void task1(){
try {
System.out.println("任务1执行:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
Thread.sleep(65000);
System.out.println("任务1结束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
同个任务的并发执行
相对同步执行来说,定时任务方法头部增加@Async即可实现并发执行,也就是严格按照cron表达式进行时间匹配执行,无需等待上一次任务执行结束。
@Component
public class taskTest {
@Async
@Scheduled(cron = "0 */1 * * * ?")
public void task1(){
try {
System.out.println("任务1执行:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
Thread.sleep(65000);
System.out.println("任务1结束:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
多个任务的同步执行
任务使用@Scheduled
然后最重要的是,需要将springboot维护的ThreadPoolTaskScheduler定时任务线程池的长度设置为大于定时任务个数的值。然后ThreadPoolTaskScheduler默认长度为1。所以默认只有一个定时任务在跑。
源码如下:
所以,需要将ThreadPoolTaskScheduler的长度修改即可,在项目启动时,设置长度,替换原本springboot管理的bean即可。
@Component
public class TaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
return threadPoolTaskScheduler;
}
}