码迷,mamicode.com
首页 > 编程语言 > 详细

⑤SpringBoot之定时任务

时间:2018-08-06 17:52:56      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:enables   util   image   task   print   rate   执行时间   framework   one   

本文介绍SpringBoot定时任务的使用,springboot默认已经帮我们实行了,只需要添加相应的注解就可以实现。

1.pom配置文件

pom包里面只需要引入springboot 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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

2、启动类启用定时

在启动类上面加上@EnableScheduling即可开启定时。

@SpringBootApplication
@EnableScheduling
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

3、创建定时任务实现类

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerTask {
    
     private int count=0;
     private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
     @Scheduled(cron="*/6 * * * * ?")
     private void process(){
        System.out.println("this is scheduler task runing  "+(count++));
     }
     
     @Scheduled(fixedRate = 6000)
     public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
     } 
}

参数说明:

@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron=”*/6 * * * * ?”,一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
fixedRate 说明
@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行;
@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行;
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次。

控制台输出:

技术分享图片

如果使用static变量,假设 private static boolean isStop=false;
在定时器的方法中首行加一行代码:if(isStop) return;
如果需要停止定时器,你写个页面,控制isStop的值就可以开关定时器了。 

 

⑤SpringBoot之定时任务

标签:enables   util   image   task   print   rate   执行时间   framework   one   

原文地址:https://www.cnblogs.com/shawWey/p/9431423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!