springboot注解添加简单的定时任务

参考文章:http://blog.didispace.com/springbootscheduled/

1.项目启动类添加开启定时任务注解(@EnableScheduling)

package com.holidaylee;

import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
public class Application {

   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }
}

2.添加定时任务,注意需要添加与@Component具有相同作用的将对象交给spring容器管理的注解

package com.holidaylee.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class ScheduleExample {

   /**
    * 上一次开始执行时间点之后5秒再执行
    */
   @Scheduled(fixedRate = 5000)
   public void fixedRateExample(){
      System.out.println("This is a fixRate schedule example");
   }

   /**
    * 上一次执行完毕时间点之后5秒再执行
    */
   @Scheduled(fixedDelay = 5000)
   public void fixedDelayExample(){
      System.out.println("This is a fixedDelay schedule example");
   }

   /**
    * 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
    */
   @Scheduled(initialDelay = 1000 ,fixedRate = 5000)
   public void initialDelayExample(){
      System.out.println("This is a initialDelay schedule example");
   }

   /**
    * 每天凌晨一点执行任务
    */
   @Scheduled(cron = "0 0 01 * * ?")
   public void cronExample() {
      System.out.println("This is a cron schedule example");
   }

}

注明:

本文为学习记录笔记,不喜勿喷。

 

 

 

你可能感兴趣的:(springboot定时任务)