版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gfd54gd5f46/article/details/77370971
GitHub 地址:
https://github.com/asd821300801/Spring-Boot.git
创建Spring Boot 基础工程
- pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
启动类开启定时调度器
- SpringbootHelloApplication.java
@SpringBootApplication
@EnableScheduling //开启定时器
public class SpringbootHelloApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloApplication.class, args);
}
}
创建定时器
- SchedulerTask1.java
包所在:com.example.task
package com.example.task;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SchedulerTask1 {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Scheduled(cron="*/5 * * * * ?")
public void dateTask(){
LOG.info("SchedulerTask1 : " + new Date().toString());
}
}
启动工程之后,5秒打印一段时间。
- SchedulerTask2.java
包所在:com.example.task
package com.example.task;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SchedulerTask2 {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Scheduled(fixedRate = 5000)
private void dateTask() {
LOG.info("SchedulerTask2 : " + new Date().toString());
}
}
启动工程之后,5秒打印一段时间。
参数说明
@Scheduled 注解
@Scheduled
注解可以接受两种定时的设置,一种是我们常用的cron="*/5 * * * * ?"
,一种是 fixedRate=5000,两种都表示每隔五秒打印一下内容。
cron 参数
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为
- 秒(0~59)
- 分钟(0~59)
- 小时(0~23)
- 天(月)(0~31,但是你需要考虑你月的天数)
- 月(0~11)
- 天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
- 7.年份(1970-2099)
fixedRate 参数
@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次