springboot基于@Scheduled注解,实现定时任务
一:导入pom依赖
引入 springboot starter包即可
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
二:启动类启用定时任务:
在启动类上加注解:@EnableScheduling即可实现。
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
三:创建定时任务实现类:
1.创建第一个定时任务
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")//启动定时任务
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}
2.创建第二个定时任务
@Component
public class Scheduler2Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}
3.运行结果如下
this is scheduler task runing 0
现在时间:09:44:17
this is scheduler task runing 1
现在时间:09:44:23
this is scheduler task runing 2
现在时间:09:44:29
this is scheduler task runing 3
现在时间:09:44:35
参数说明:
@Scheduled接受两种定时的设置:
一种是cornexpression。
一种是Rate/Delay表达式(毫秒值):
@Scheduled(fixedRate = 6000):上一次开始执行时间点后每隔6秒执行一次。
@Scheduled(fixedDelay = 6000):上一次执行完毕时间点之后6秒再执行。
@Scheduled(initialDelay=1000, fixedRate=6000):第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次。
cornExpression表达式详解
ronExpression定义时间规则,Cron表达式由6或7个空格分隔的时间字段组成:秒 分钟 小时 日期 月份 星期 年(可选);
完整字段:[秒] [分] [小时] [日] [月] [周] [年]
字段 允许值 允许特殊字符E
秒 0-59 , - * /
分 0-59 , - * /
小时 0-23 , - * /
日 1-31 , - * ? / L W C
月 1-12或JAN-DEC , - * /
周 1-7或SUN-SAT , - * ? / L C #
年 留空或1970-2099 , - * /
https://blog.youkuaiyun.com/supingemail/article/details/22274279 大家可以去看看这个人的文章,里面对这些表达式、注解讲的挺详细的
注:
*表示所有值,在分钟里表示每一分钟触发。在小时,日期,月份等里面表示每一小时,每一日,每一月。
?表示不指定值。表示不关心当前位置设置的值。 比如不关心是周几,则周的位置填写?。 主要是由于日期跟周是有重复的所以两者必须有一者设置为?
- 表示区间。小时设置为10-12表示10,11,12点均会触发。
,表示多个值。 小时设置成10,12表示10点和12点会触发。
/ 表示递增触发。 5/15表示从第5秒开始,每隔15秒触发。
L 表示最后的意思。 日上表示最后一天。星期上表示星期六或7。 L前加数据,表示该数据的最后一个。
星期上设置6L表示最后一个星期五。 6表示星期五
W表示离指定日期最近的工作日触发。15W离该月15号最近的工作日触发。
#表示每月的第几个周几。 6#3表示该月的第三个周五。