SpringBoot定时器
@Scheduled:
- @Scheduled(fixedRate=3000):上一次开始执行时间点后3秒再次执行;
- @Scheduled(fixedDelay=3000):上一次执行完毕时间点3秒再次执行;
- @Scheduled(initialDelay=1000, fixedDelay=3000):第一次延迟1秒执行,然后在上一次执行完毕时间点3秒再次执行;
- @Scheduled(cron="* * * * * ?"):按cron规则执行;
@EnableScheduled:发现@Scheduled注解任务并执行
1.首先先创建一个springboot项目
2.在Application设置启动启动定时作用的功能
package com.ytzl.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
3.创建实现类
package com.ytzl.springboot.scheduler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 作者: fyq
* 时间: 2020/8/21 0021 14:42
* 描述: 定时器
*/
@Component
@Slf4j
public class Scheduler {
private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void testTasks(){
log.info("定时任务执行时间:"+dateFormat.format(new Date()));
}
}
注意:
需要在具体实现类中加上@Componeent注解,其中@Slf4j是日志记录。
4.运行结果:
还可以设置每天定时执行任务
在实现类中加入以下代码
@Scheduled(cron ="0 19 23 ? * *" )
public void testTimeTask(){
//每天23:19整执行一次
log.info("定时任务执行时间:"+dateFormat.format(new Date()));
}
运行结果如下:
cron规则
“*”字符代表所有可能的值(位置不同,取值范围不同)
“/”字符用来指定数值的增量(区间)
“?”字符仅被用于天(月)和天(星期)两个子表达式,表示不指定值
“L” 字符仅被用于天(月)和天(星期)两个子表达式,即英文单词last
-
用在月份上:2L表示月份的最后l两天
-
用在天数上:2L表示这个星期最后两天
cron表达式中各时间元素即 * ,使用空格进行分割,表达式有至少6个(也可能7个)取值范围为:
秒(0~59)
分钟(0~59)
小时(0~23)
天(每个月天数,28~31)
月(0~11)
天(星期)(1~7 或 SUN,MON,TUE,WED,THU,FRI,SAT)
年份(1970-2099)