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

  • 相关阅读:
    UGUI组件之Slider组件简单笔记
    UGUI事件之Drag拖拽事件
    C#的数据类型之最常用的几种类型
    UGUI组件之Text文本组件简单笔记
    UGUI组件之Toggle 组件简单笔记
    Print 与Debug.Log的区别
    Unity脚本用VS打开出现 "以下文件中的行尾不一致,要将行尾标准化吗?"
    UGUI组件之Image 组件简单笔记
    UGUI事件之Pointer指针事件
    定制自己的Unity脚本模板
  • 原文地址:https://www.cnblogs.com/shawWey/p/9431423.html
Copyright © 2011-2022 走看看