springboot implements timer

1. Create a spring boot project and add dependencies in pom.xml:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.1.RELEASE</version>
</parent>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</java.version>
</properties>
<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. Startup class start timing:

/**
 * Startup class
 */
 @SpringBootApplication
 //Enable timing
 @EnableScheduling
 public class Application {

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

}

3. Create a timed task implementation class:

/**
 * Scheduled task class 1
 * Created by ASUS on 2018/5/6
 *
 * @Authod Grey Wolf
 */
 //To be declared as a bean, the timing effect cannot be achieved without declaring the startup class to start
 @Component
 public class SchedulerTask {

    private int count = 0 ;
 //Indicates printing every 6 seconds
 @Scheduled ( cron = "*/6 * * * * ?" )
     private void procedures (){
        

        System.out.println("this is a scheduler task running:"+(count++));
    }
}
/**
 * 定时任务类2
 * Created by ASUS on 2018/5/6
 *
 * @Authod Grey Wolf
 */
//要声明为bean,没有声明启动类启动无法实现定时效果
@Component
public class Scheduler2Task {
    private  static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");

    //表示每隔6秒打印一次
    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime(){
        System.out.println("现在时间:"+dataFormat.format(new Date()));
    }
}

4.run启动类application.class 测试效果:


参数说明

@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。

fixedRate 说明

  • @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行

  • @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行

  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次

我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325819299&siteId=291194637