zoukankan      html  css  js  c++  java
  • Springboot的定时任务:@Scheduled @EnableScheduling注解

    转自:https://blog.csdn.net/weweeeeeeee/article/details/91444616

    在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容, Spring Boot 默认已经帮我们实行了,只需要添加相应的注解就可以实现

    1、pom 包配置

    pom 包里面只需要引入 Spring Boot Starter 包即可

    1.  
      <dependencies>
    2.  
      <dependency>
    3.  
      <groupId>org.springframework.boot</groupId>
    4.  
      <artifactId>spring-boot-starter</artifactId>
    5.  
      </dependency>
    6.  
      <dependency>
    7.  
      <groupId>org.springframework.boot</groupId>
    8.  
      <artifactId>spring-boot-starter-test</artifactId>
    9.  
      <scope>test</scope>
    10.  
      </dependency>
    11.  
      </dependencies>

    2、启动类启用定时

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

    1.  
      @SpringBootApplication
    2.  
      @EnableScheduling
    3.  
      public class Application {
    4.  
       
    5.  
      public static void main(String[] args) {
    6.  
      SpringApplication.run(Application.class, args);
    7.  
      }
    8.  
      }

    3、创建定时任务实现类

    定时任务1:

    1.  
      @Component
    2.  
      public class SchedulerTask {
    3.  
       
    4.  
      private int count=0;
    5.  
       
    6.  
      @Scheduled(cron="*/6 * * * * ?")
    7.  
      private void process(){
    8.  
      System.out.println("this is scheduler task runing "+(count++));
    9.  
      }
    10.  
       
    11.  
      }

    定时任务2:

    1.  
      @Component
    2.  
      public class Scheduler2Task {
    3.  
       
    4.  
      private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    5.  
       
    6.  
      @Scheduled(fixedRate = 6000)
    7.  
      public void reportCurrentTime() {
    8.  
      System.out.println("现在时间:" + dateFormat.format(new Date()));
    9.  
      }
    10.  
       
    11.  
      }

    结果如下:

    1.  
      this is scheduler task runing 0
    2.  
      现在时间:09:44:17
    3.  
      this is scheduler task runing 1
    4.  
      现在时间:09:44:23
    5.  
      this is scheduler task runing 2
    6.  
      现在时间:09:44:29
    7.  
      this is scheduler task runing 3
    8.  
      现在时间:09:44:35

    --------------------------------------------------- 

  • 相关阅读:
    Unique Encryption Keys 暴力学习map,vector 函数
    hdu 1250 Hat's Fibonacci
    匈牙利算法模板 图的二分匹配 hdu 2063 过山车
    hdu 4260 汉诺塔问题 The End of The World
    各种常见文件的hex文件头
    Ubuntu & node.js
    Linux周期性任务的执行指令配置
    MySQL各版本的性能特性(从4.0版本开始)
    Tsung 1.5.0 增加对 WebSocket 和 BOSH 的支持
    ShowSlow+Yslow环境搭建
  • 原文地址:https://www.cnblogs.com/sharpest/p/13705092.html
Copyright © 2011-2022 走看看