为了学习SpringBoot,将平时学到的记录下来。本文将详细讲述如何使用注解来完成一个定时执行功能。
1、准备工作
首先,创建一个maven项目,如何创建maven项目请参考:https://blog.csdn.net/chenzz2560/article/details/83270232。在创建完maven项目后,在pom.xml中导入SpringBoot运行需要的依赖包。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>czz.study</groupId>
<artifactId>scheduled</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、创建要运行的程序
创建一个class类,里面包含了你要定时运行的方法。@Component 注解将这个类声明为一个Bean对象,交给Spring进行管理,@Scheduled 注解声明了这个方法是一个定时方法,cron属性表明了这个方法运行的规则,test1表明每10秒运行一次,test2表明每9秒运行一次,这个可以通过cron在线生成。
package czz.study.schdule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestSchdule {
@Scheduled(cron = "0/10 * * * * ? ")
private void test1() {
System.out.println("定时器1定时运行");
}
@Scheduled(cron = "0/9 * * * * ? ")
private void test2() {
System.out.println("定时器2定时运行");
}
}
3、运行程序
创建一个启动类,@SpringBootApplication 功能相当于@Configuration,@EnableAutoConfiguration,@ComponentScan这三个注解,SpringApplication.run(Main.class, args)这行代码用来声明项目入口,没有这行代码,使用的Spring注解都会失效(等于没有注解)。@EnableScheduling用来声明 @Scheduled注解可用,只有添加了@EnableScheduling,程序才会定时运行被@Scheduled注解的方法。
package czz.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
4、运行结果
从结果可以看出,test1从0秒开始,每10秒运行一次,test2从0秒开始,每9秒运行一次。
总结:除了使用cron表达式,Schedule还可以使用fixedRate(每隔多少毫秒执行),fixedDelay(每次执行任务之后间隔多久毫秒再次执行该任务)等方法来操控方法执行的频率。