SpringBoot@Schedule入门基础
前言
Schedule是一个任务调度器,SpringBoot中可定时触发执行定时任务。
一、基本概念
在SpringBoot中,使用 @Scheduled 注解就能很方便地创建一个定时任务。
包括有:
- 固定速率执行
- 固定延迟执行
- 初始延迟执行
- Cron 表达式执行
cron表达式
Cron表达式由6~7项组成,中间用空格分开。从左到右依次是:秒、分、时、日、月、周几、年(可省略)。值可以是数字,也可以是以下符号:
*:所有值都匹配
?:无所谓,不关心,通常放在“周几”里
,:或者
/:增量值
-:区间下面举几个例子,看了就知道了:
0 * * * * *:每分钟(当秒为0的时候)
0 0 * * * *:每小时(当秒和分都为0的时候)
*/10 * * * * *:每10秒
0 5/15 * * * *:每小时的5分、20分、35分、50分
0 0 9,13 * * *:每天的9点和13点
0 0 8-10 * * *:每天的8点、9点、10点
0 0/30 8-10 * * *:每天的8点、8点半、9点、9点半、10点
0 0 9-17 * * MON-FRI:每周一到周五的9点、10点…直到17点(含)
0 0 0 25 12 ?:每年12约25日圣诞节的0点0分0秒(午夜)
0 30 10 * * ? 2016:2016年每天的10点半
使用栗子:
/**
* fixedRate:固定速率执行。每5秒执行一次。
*/
@Scheduled(fixedRate = 5000)
/**
* fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
*/
@Scheduled(fixedDelay = 2000)
/**
* initialDelay:初始延迟。任务的第一次执行将延迟5秒,然后将以5秒的固定间隔执行。
*/
@Scheduled(initialDelay = 5000, fixedRate = 5000)
/**
* cron:使用Cron表达式。 每分钟的1,2秒运行
*/
@Scheduled(cron = "1-2 * * * * ? ")
二、使用方法
1-启动类或者配置类加上@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2-在加入容器的类中,方法上使用@Scheduled
@Scheduled(fixedDelay = 2000)
public void reportCu(){
}
三、@EnableAsync 和 @Async 使定时任务并行执行
Schedule的任务默认是单线程执行
@Component
@EnableAsync
public class AsyncScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(AsyncScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
/**
* fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
*/
//@Async
@Scheduled(fixedDelay = 2000)
public void reportCurrentTimeWithFixedDelay() {
try {
TimeUnit.SECONDS.sleep(3);
log.info("Fixed Delay Task : The time is now {}", dateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
参考或相关文章
- https://segmentfault.com/a/1190000020192878
- http://qinghua.github.io/spring-scheduler/

本文详细介绍了SpringBoot中定时任务的实现方式,包括@Scheduled注解的使用方法、Cron表达式的解析及如何通过@EnableAsync和@Async实现定时任务的并行执行。
1202

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



