一、@Scheduled
- 默认是串行的,单线程,当开启多个任务时,任务的执行时机会受上一个任务执行时间的影响
@Configuration
@EnableScheduling //开启定时任务
public class ScheduleTask {
//每10秒执行一次
@Scheduled(cron = "0/10 * * * * ?")
private void configureTasks() {
System.out.println("我是一个定时任务");
}
}
- @Scheduled 除了cron还提供另外三种种方式: fixedRate,fixedDelay,initialDelay
1、 fixedDelay
- 控制方法执行的间隔时间,是以上一次方法执行完开始算起,如上一次方法执行阻塞住了,那么直到上一次执行完,并间隔给定的时间后,执行下一次
2、fixedRate
- 按照一定的速率执行,是从上一次方法执行开始的时间算起,如果上一次方法阻塞住了,下一次也是不会执行,但是在阻塞这段时间内累计应该执行的次数,当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行
3、initialDelay
- 表示在容器启动后,延迟10秒后再执行一次定时器
4、实际使用
// 容器启动后,延迟10秒后再执行一次定时器,以后每24小时再执行一次该定时器
@Scheduled(initialDelay = 1000 * 10, fixedRate = 1000 * 60 * 60 * 24)
二、多线程定时任务
- @Scheduled执行周期任务会受到上一个任务的执行时间影响
- @EnableAsync可以开启多线程执行周期任务
@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
@Configuration
public class MultiThreadScheduleTask {
@Async
@Scheduled(fixedDelay = 1000)
public void first() throws InterruptedException {
System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
Thread.sleep(1000 * 10);
}
@Async
@Scheduled(fixedDelay = 2000)
public void second() {
System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
}
}
三、配置环境开关
- 在实际开发中,我们通常需要配置定时任务的执行环境
@Configuration
// 开启定时任务
@EnableScheduling
// 配置文件读取是否启用此配置
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class ScheduleTask {
@Scheduled(initialDelay = 5*1000,fixedRate = 5*1000)
private void task(){
System.out.println("我是一个定时任务。。。。");
}
}
- application.properties
spring.profiles.active=dev
- application-dev.properties
server.port=9007
spring.profiles=dev
- application-prod.properties
server.port=9008
spring.profiles=prod
## 开启定时任务
scheduling.enabled = true
- 直接启动会使用默认的dev配置,生产环境在启动命令上指定prd配置
java -jar my.jar --spring.profiles.active=prd