SpringBoot集成Quartz
定时任务Quartz : 就是在指定的时间执行一次或者循环执行,在项目的开发中有时候会需要的, 还是很有用的.
SpringBoot内置的定时
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
2.启动类上添加注解
@SpringBootApplication
@EnableScheduling
public class SpringbootQuartzApplication {
}
3.创建定时执行的任务类(两种方式)
方式一:
@Component
public class SchedulerTask {
private int count = 0;
/**
* @Author Smith
* @Description 设置没6秒执行一次
* @Date 14:23 2019/1/24
* @Param
* @return void
**/
@Scheduled(cron = "*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task running " + (count++));
}
}
方式二:
@Component
public class SchedulerTask2 {
private static final SimpleDateFormat dateFormat =
new SimpleDateFormat("HH:mm:ss");
/**
* @Author Smith
* @Description 设置没6秒执行一次
* @Date 14:22 2019/1/24
* @Param
* @return void
**/
@Scheduled(fixedRate = 6000)
private void process(){
System.out.println("now time is " + dateFormat.format(new Date()));
}
}
参数说明
@Scheduled 参数可以接受两种定时的设置,一种是我们常用的 cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都可表示固定周期执行定时任务。
fixedRate说明
@Scheduled(fixedRate = 6000):上一次开始执行时间点之后 6 秒再执行。
@Scheduled(fixedDelay = 6000):上一次执行完毕时间点之后 6 秒再执行。
@Scheduled(initialDelay=1000, fixedRate=6000):第一次延迟 1 秒后执行,之后按 fixedRate 的规则每 6 秒执行一次。
cron说明
cron一定有七位数,最后一位是年,SpringBoot定时方案只需要设置六位即可:
第一位, 表示秒, 取值是0 ~ 59
第二位, 表示分. 取值是0 ~ 59
第三位, 表示小时, 取值是0 ~ 23
第四位, 表示天