Boot 定时任务
在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容, Spring Boot 默认已经帮我们实行了,只需要添加相应的注解就可以实现。
一、引入相关依赖包
又到了Spring Boot 最擅长的环节了:依赖包,只要在Pom.xml中<dependencies>和</dependencies>之间加入依赖语句,IDEA就会帮我们自动从网上下载相关依赖包。这种强大的功能,站长觉得是Spring Boot的核心优势之一。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
二、在主程序上加上自动任务的注解
在启动类上面加上@EnableScheduling 注解,表示程序启动时,就开启定时任务。当然,需要导入下面的包:
- import org.springframework.scheduling.annotation.EnableScheduling;
然后,把这个注解放在之前加上的 @MapperScan("com.w3xue.jiaocheng.mapper") 注解平行的位置:
- @MapperScan("com.w3xue.jiaocheng.mapper")
- @SpringBootApplication
- @EnableScheduling
- public class JiaochengApplication extends SpringBootServletInitializer {
- ...
- }
三、创建定时任务实现类
为了方便管理,我们在程序的主文件夹新建一个文件夹“task”,然后在其中新建2个自动任务类 SchedulerTask类 和 Scheduler2Task类。
SchedulerTask类:
- package com.w3xue.jiaocheng.task;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- @Component
- public class SchedulerTask {
- private int count=0;
- @Scheduled(cron="*/6 * * * * ?")
- private void process(){
- System.out.println("this is scheduler task runing "+(count++));
- }
- }
Scheduler2Task类:
- package com.w3xue.jiaocheng.task;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- @Component
- public class Scheduler2Task {
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
- @Scheduled(fixedRate = 6000)
- public void reportCurrentTime() {
- System.out.println("现在时间:" + dateFormat.format(new Date()));
- }
- }
然后启动主程序,就会发现,在IDEA的Console面板中,会不停的打印上面规定的语句,说明定时任务在执行:
- this is scheduler task runing 0
- 现在时间:17:24:07
- this is scheduler task runing 1
- 现在时间:17:24:13
- this is scheduler task runing 2
- 现在时间:17:24:19
- this is scheduler task runing 3
- 现在时间:17:24:25
我们只需要把这些打印任务,换成我们想要进行的羞羞操作,就可以去睡大觉了。
四、参数说明
@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
fixedRate 说明
@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按 fixedRate 的规则每6秒执行一次
参考来源:https://www.cnblogs.com/ityouknow/p/6132645.html
转载本站内容时,请务必注明来自W3xue,违者必究。