1、整合定时任务
1)使用注解@EnableScheduling 开启定时任务,会自动扫描
2)在类前添加@Componet注解声明为组件被容器扫描
3)在定时任务方法前添加@Scheduled(fixedRate =时长) 或者 @Scheduled(fixedDelay =时长) 设置定时任务启动的时间间隔
间隔设置的区别:
fixedDelay 间隔时间表示是根据上次的任务结束时开始计时。如果间隔时间设为5分钟,那么当本次任务的方法执行结束后才开始计算间隔5分钟后,再次执行下一次任务。
fixedRate 间隔时间是根据上次任务开始的时候计时的(下文有介绍如何开启异步执行任务)。
程序示例:
@SpringBootApplication
@ComponentScan(basePackages = { "com.test" })
@EnableScheduling //开启定时任务
public class TestApplication{
public static void main(final String[] args) {
SpringApplication.run(TestApplication.class,args);
}
}
@Component
public class TestTask {
public static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
//定义每过3秒执行任务
@Scheduled(fixedRate=3000)
public void test(){
System.out.println("当前时间:" + sdf.format(new Date()));
}
}
2、还可以以表达式的形式定义执行时间,获取到Cron表达式后填入@Scheduled 中 获取表达式网址:http://cron.qqe2.com
程序示例:
@Component
public class TestTask {
public static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
//自定义的时间
@Scheduled(cron = "21/59 * * * * ? *")
public void test(){
System.out.println("当前时间:" + sdf.format(new Date()));
}
}
3、SpringBoot整合异步任务
@Scheduled(fixedRate),它的间隔时间是根据上次任务开始的时候计时的。如果避免任务被阻塞需要开启异步执行任务。
在启动类 上加入 @EnableAsync 开启异步,会自动扫描 @Component注解的类,@Async注解方法 (多个有该注解的方法会同时启动)
加了注解以后,就开启了多线程模式,当到了下一次任务的执行时机时,如果上一次任务还没执行完,就会自动创建一个新的线程来执行它。异步执行也可以理解为保证了任务以固定速度执行。
开启多线程后,每次任务开始的间隔都是一样的。