Spring Boot(九):定时任务
在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容, Spring Boot 默认已经帮我们实行了,只需要添加相应的注解就可以实现
1、pom 包配置
pom 包里面只需要引入 Spring Boot Starter 包即可
<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>
</dependencies>
2、启动类启用定时
在启动类上面加上@EnableScheduling
即可开启定时
@SpringBootApplication
@EnableScheduling
public class Application {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
SpringApplication.run(Application.class, args);
}
}
3、创建定时任务实现类
定时任务 1:
@Component
public class SchedulerTask {
<span class="hljs-keyword">private</span> <span class="hljs-type">int</span> count=<span class="hljs-number">0</span>;
<span class="hljs-meta">@Scheduled(cron="*/6 * * * * ?")</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">process</span><span class="hljs-params">()</span>{
System.out.println(<span class="hljs-string">"this is scheduler task runing "</span>+(count++));
}
}
定时任务 2:
@Component
public class Scheduler2Task {
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">SimpleDateFormat</span> <span class="hljs-variable">dateFormat</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleDateFormat</span>(<span class="hljs-string">"HH🇲🇲ss"</span>);
<span class="hljs-meta">@Scheduled(fixedRate = 6000)</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">reportCurrentTime</span><span class="hljs-params">()</span> {
System.out.println(<span class="hljs-string">"现在时间:"</span> + dateFormat.format(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>()));
}
}
结果如下:
this is scheduler task runing 0
现在时间:09:44:17
this is scheduler task runing 1
现在时间:09:44:23
this is scheduler task runing 2
现在时间:09:44:29
this is scheduler task runing 3
现在时间:09:44:35
参数说明
@Scheduled
参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?"
, 一种是 fixedRate = 6000
,两种都表示每隔六秒打印一下内容。
fixedRate 说明
@Scheduled(fixedRate = 6000)
:上一次开始执行时间点之后 6 秒再执行@Scheduled(fixedDelay = 6000)
:上一次执行完毕时间点之后 6 秒再执行@Scheduled(initialDelay=1000, fixedRate=6000)
:第一次延迟 1 秒后执行,之后按 fixedRate 的规则每 6 秒执行一次
文章内容已经升级到 Spring Boot 2.x