Springboot整合Quartz实现定时任务调度

在开发中,越来越多的公司使用springboot,而在项目中又会使用到任务调度框架Quartz,所以今天就使用一个Demo来实现springboot与Quartz的整合。
首先创建一个java项目,使用maven进行版本控制。
在pom.xml加入依赖

[XML]纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<!--配置父级工程-->

<`parent`>

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

<`artifactId>spring-boot-starter-parent</artifactId`>

<`version>2.0.3.RELEASE</version`>

</`parent`>

<!--配置WEB启动器 SpringMVC、Restful、jackson-->

<`dependencies`>

<`dependency`>

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

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

</`dependency`>

<!--配置springboot热部署-->

<`dependency`>

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

<`artifactId>spring-boot-devtools</artifactId`>

</`dependency`>

<!--任务调度:quartz-->

<`dependency`>

<`groupId>org.quartz-scheduler</groupId`>

<`artifactId>quartz</artifactId`>

</`dependency`>

</`dependencies`>

<!--配置全局属性-->

<`properties`>

<!--配置jdk版本-->

<`java.version>1.8</java.version`>

</`properties`>

<!--配置maven插件-->

<`build`>

<`plugins`>

<`plugin`>

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

<`artifactId>spring-boot-maven-plugin</artifactId`>

</`plugin`>

</`plugins`>

</`build`>

创建一个类,类似于你要调度的任务

[Java]纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

import java.util.Date;

/**

* Date:2018/7/22

* Author:FireDragon-WuJianHui

* Desc:设置项目

*/

@Component`//组件`

public class DemoOfQuartz {

//每一分钟执行一次

@Scheduled`(cron = "0 0/1 * ?"`)

public void work() throws Exception{

System.out.println(`"在 "+new Date()+" 调用了work的方法");`

}

//每5秒执行一次

@Scheduled`(fixedRate = 5000`)

public void eat() throws Exception{

System.out.println(`"在 "+new Date()+" 调用了eat的方法");`

}

//每4秒执行一次

@Scheduled`(cron = "0/4 ?"`)

public void sleep() throws Exception{

System.out.println(`"在 "+new Date()+" 调用了sleep的方法");`

}

}

最后创建springboot启动类,运行

[Java]纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

/**

* Date:2018/7/22

* Author:FireDragon-WuJianHui

* Desc:

*/

@SpringBootApplication

public class SpringBootStratApplication {

public static void main(String[] args){

//启动springboot程序

SpringApplication.run(SpringBootStratApplication.`class`);

}

}

注意:以上两个类要在同一个包下面,要不然不会生效

评论

暂无评论