好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot整合定时任务之实现Scheduled注解的过程(一个注解全解决)

一、使用场景

定时任务在开发中还是比较常见的,比如:定时发送邮件,定时发送信息,定时更新资源,定时更新数据等等...

二、准备工作

在Spring Boot程序中不需要引入其他Maven依赖
(因为spring-boot-starter-web传递依赖了spring-context模块)

?

1

2

3

4

<dependency>

     <groupId>org.springframework.boot</groupId>

     <artifactId>spring-boot-starter-web</artifactId>

</dependency>

三、开始搭建配置配置启动项

配置启动项

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

package com.wang.test.demo;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableScheduling;

 

@SpringBootApplication

@EnableScheduling //启动定时任务

public class DemoApplication {

 

     public static void main(String[] args) {

         SpringApplication.run(DemoApplication. class , args);

     }

 

}

cron表达式

关于cron表达式,小编这里不做过多介绍,这里是cron生成器,大家可以参考

https://HdhCmsTestmatools测试数据/cron/

定时任务方法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package com.wang.test.demo.task;

 

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

 

@Component //加载到容器中,可以被发现启动

public class TaskTest {

 

     //cron表达式,来控制定时执行时间,这里是每5秒执行一次本方法,业务逻辑可以进行在此方法内进行书写

     @Scheduled (cron = "0/5 * * * * ?" )

     public void printTimeOne(){

 

         System.out.println( "任务一:时间为-->" +System.currentTimeMillis());

     }

 

     @Scheduled (cron = "0/6 * * * * ?" )

     public void printTimeTwo(){

 

         System.out.println( "任务二:时间为-->" +System.currentTimeMillis());

 

     }

 

}

四、结果展示

五、总结

这样就完整了SpringBoot整合定时任务了,一个注解全搞定,非常简洁好懂.

到此这篇关于SpringBoot整合定时任务之实现Scheduled注解的过程(一个注解全解决)的文章就介绍到这了,更多相关SpringBoot整合定时任务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestcnblogs测试数据/wang1221/p/15236748.html

查看更多关于SpringBoot整合定时任务之实现Scheduled注解的过程(一个注解全解决)的详细内容...

  阅读:16次