一. 项目示例
1.1 pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
1.2 创建一个定时类
/**
* @author: hejr
* @desc:
* @date: 2019/4/16 15:30
*/
@Component
@Slf4j
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
/**
* 每隔5秒钟触发一次
*/
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("现在时间:" + dateFormat.format(new Date()));
}
/**
* 通过cron来设置定时规则,每隔10秒
* 对应含义为:
* 字段 允许值 允许的特殊字符
秒 0-59 , - * /
分 0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /
*/
@Scheduled(cron = "0/10 * * * * ?")
public void executeByTenSecond() {
log.info("通过cron来设置每隔10s执行...");
}
}
如果想深入了解定时规则,可阅读源码Scheduled注解中相关的类,比如想看cron的定时规则,则可以查看如下:
1.3 启动类配置
@SpringBootApplication
@EnableScheduling
public class Springboot2009Application {
public static void main(String[] args) {
SpringApplication.run(Springboot2009Application.class, args);
}
}
1.4 运行效果
一个是每隔5秒触发,一个是每隔10秒触发。
二. 源码下载
https://gitee.com/hejr.cn.com/SpringBoot2.0_2019/tree/master/springboot2_009