zoukankan      html  css  js  c++  java
  • ⑤SpringBoot之定时任务

    本文介绍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的值就可以开关定时器了。 

  • 相关阅读:
    值得推荐的C/C++框架和库
    P2P技术基础: 关于TCP打洞技术
    Java FileInputStream与FileReader的区别
    如何理解java采用Unicode编码
    细说:Unicode, UTF-8, UTF-16, UTF-32, UCS-2, UCS-4
    程序员趣味读物:谈谈Unicode编码
    字符编码笔记:ASCII,Unicode 和 UTF-8
    Java并发编程:volatile关键字解析(转)
    java线程安全问题之静态变量、实例变量、局部变量
    Hystrix使用详解
  • 原文地址:https://www.cnblogs.com/shawWey/p/9431423.html
Copyright © 2011-2022 走看看