zoukankan      html  css  js  c++  java
  • SpringBoot(一) 添加定时任务

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

    一.构建项目,如图所示:

        

     创建一个用于执行定时任务的接口,以及一个接口的实现类。

    二.添加注解

          在启动类添加定时注解 @EnableScheduling

         

    在实现类添加定时任务,哪个方法需要执行定时任务,则添加到哪个方法上。

    1.  
      import com.example.smalserver.http.service.server.TimingService;
    2.  
      import org.springframework.scheduling.annotation.Scheduled;
    3.  
      import org.springframework.stereotype.Component;
    4.  
      import org.springframework.stereotype.Service;
    5.  
       
    6.  
      /**
    7.  
      * @Author: caohuijie
    8.  
      * @Date: 创建日期 2018/11/7
    9.  
      * @Modified By:
    10.  
      * @Description: 定时任务类
    11.  
      */
    12.  
      @Component
    13.  
      @Service
    14.  
      public class TimingServiceImpl implements TimingService {
    15.  
       
    16.  
      private int count=0;
    17.  
       
    18.  
      @Scheduled(cron="*/6 * * * * ?")
    19.  
      @Override
    20.  
      public void timingTask() {
    21.  
      System.out.println("this is scheduler task runing "+(count++));
    22.  
      }
    23.  
      }

     或者:

    1.  
      import com.example.smalserver.http.service.server.TimingService;
    2.  
      import org.springframework.scheduling.annotation.Scheduled;
    3.  
      import org.springframework.stereotype.Component;
    4.  
      import org.springframework.stereotype.Service;
    5.  
       
    6.  
      /**
    7.  
      * @Author: caohuijie
    8.  
      * @Date: 创建日期 2018/11/7
    9.  
      * @Modified By:
    10.  
      * @Description: 定时任务类
    11.  
      */
    12.  
      @Service
    13.  
      public class TimingServiceImpl implements TimingService {
    14.  
       
    15.  
      private int count=0;
    16.  
       
    17.  
      @Scheduled(cron="*/6 * * * * ?")
    18.  
      @Override
    19.  
      public void timingTask() {
    20.  
      System.out.println("this is scheduler task runing "+(count++));
    21.  
      }
    22.  
      }

    corn表达式:

    "0 0 * * * *" 表示每小时0分0秒执行一次

    " */10 * * * * *" 表示每10秒执行一次

    "0 0 8-10 * * *" 表示每天8,9,10点执行

    "0 0/30 8-10 * * *" 表示每天8点到10点,每半小时执行

    "0 0 9-17 * * MON-FRI" 表示每周一至周五,9点到17点的0分0秒执行

    "0 0 0 25 12 ?" 表示每年圣诞节(12月25日)0时0分0秒执行

  • 相关阅读:
    Circular dependency issuse on cocoapods version(0.36.0) 全然解决方式(非降版本号)
    Android Studio经常使用配置及使用技巧(二)
    poj 2195 Going Home(最小费最大流)
    OpenFace库(Tadas Baltrusaitis)中基于Haar Cascade Classifiers进行人脸检測的測试代码
    Divisibility by Eight
    hdu 5055(坑)
    微服务(Microservices)
    mysql 运行计划explain具体解释
    URAL 题目1297. Palindrome(后缀数组+RMQ求最长回文子串)
    Windows下将nginx安装为服务运行
  • 原文地址:https://www.cnblogs.com/gakuki/p/13678086.html
Copyright © 2011-2022 走看看