一、使用Spring Task
Spring 3.0以后自带了 task 调度工具,使用比 Quartz简单方便,使用 @Scheduled 注解。
1、创建一个 SpringBoot项目,引入spring-boot-starter-web依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 在启动类上添加 @EnableScheduling 注解,表示开启定时任务。
@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}
- 了解 @Scheduled 注解
在方法上使用 @Scheduled 注解表示开启一个定时任务:下面参数单位都是毫秒
- fixedRate:表示按一定频率来执行定时任务,具体是指两次任务的开始时间间隔,即第二次任务开始时,第一次任务可能还没结束。
- fixedDelay:表示按一定时间间隔来执行定时任务,具体是指本次任务结束到下次任务开始之间的时间间隔。该属性还可以配合initialDelay使用, 定义该任务延迟执行时间。
- initialDelay:表示首次任务启动的延迟时间。与fixedDelay配合使用。
- cron:通过 cron 表达式来配置任务执行时间,cron 表达式格式为:[秒] [分] [小时] [日] [月] [周] [年]
2、单线程执行任务
使用同一个线程中串行执行,如果只有一个定时任务,这样做肯定没问题,当定时任务增多,如果一个任务卡死,会导致其他任务也无法执行。
- 创建一个类,配置定时任务
@Component
public class Task1 {
@Scheduled(fixedRate = 2000)
public void fixedRateTask() {
System.out.println("fixedRateTask定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
}
@Scheduled(fixedDelay = 2000)
public void fixedDelayTask1() {
System.out.println("fixedDelayTask1111定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
}
@Scheduled(initialDelay = 2000,fixedDelay = 2000)
public void initialDelayTask2() throws InterruptedException {
System.out.println("initialDelayTask2222定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(15);
}
@Scheduled(cron = "0/5 * * * * ?")
public void cron() {
System.out.println("cron定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
}
}
2.启动项目,定时任务就开始工作了
- 可以看到使用的是同一个线程,并出现了任务阻塞的情况。

3、多线程执行任务
Spring Task 默认是单线程的,想要改成多线程,
给Spring Task提供一个多线程的TaskScheduler,Spring已经有默认实现。
- 方式一
创建配置类,@EnableAsync注解:表示开启异步事件的支持
@Configuration
@EnableAsync // 开启异步事件的支持
public class AsyncTaskConfig {
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCa

837

被折叠的 条评论
为什么被折叠?



