Spring Boot 简单实现定时任务

在Spring boot中实现定时任务,并不需要特定的依赖jar包

1 <dependency>
2             <groupId>org.springframework.boot</groupId>
3             <artifactId>spring-boot-starter</artifactId>
4 </dependency>

也不需要额外的任何配置

第一步,在项目入口类Application上增加注解@EnableScheduling

1 @SpringBootApplication
2 @EnableScheduling       //开启定时任务的注解
3 public class SpringbootdemoApplication {
4 
5     public static void main(String[] args) {
6         SpringApplication.run(SpringbootdemoApplication.class, args);
7     }
8 
9 }

第二步,在需要定时执行的方法上加上注解@Scheduled()

 1 @Slf4j
 2 @Component
 3 public class ScheduledTask {
 4 
 5     /**
 6      * Cron 表达式 cron = "* * * * * * *"
 7      * 对应关系 秒 分 小时 日期 月份 星期 年
 8      * 参考博客 https://www.cnblogs.com/javahr/p/8318728.html
 9      */
10 
11 
12 
13     @Scheduled(cron = "0/10 * * * * *")  //每10秒钟触发一次
14     public void task1() {
15         log.error("-------------this is task 1----------------");
16     }
17 
18     @Scheduled(cron = "0 27 10 * * *")   //每天上午10:27触发一次
19     public void task2() {
20         log.error("-------------this is task 2----------------");
21     }
22 
23     @Scheduled(cron = "0 30 10 5 * *")   //每月5号10:30触发一次
24     public void task3() {
25         log.error("-------------this is task 3----------------");
26     }
27 
28     /**
29      * fixedRate=6000 上一次开始执行时间点之后6秒
30      * fixedDelay=6000 上一次执行完毕时间点之后6秒
31      * initialDelay=1000, fixedRate=6000 第一次延迟一秒后执行
32      */
33 
34     @Scheduled(fixedRate = 3000)
35     public void task4() {
36         log.error("-------------this is task 4----------------");
37     }
38 
39 }

cron表达式请参考 https://www.cnblogs.com/javahr/p/8318728.html

欢迎指正交流!

原文地址:https://www.cnblogs.com/JINJAY/p/10818168.html