Spring Boot 系列教程13-注解定时任务

注解 @Scheduled(cron = “0/5 * * * * ?”)

相当于原来的xml版本的如下配置

<task:scheduled ref="scheduledTask" method="getTask1" cron="0/5 * * * * ?" />

ScheduledTask

package com.jege.spring.boot.task;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:从配置文件加载任务信息
 */
@Component
public class ScheduledTask {

  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

  @Scheduled(fixedDelayString = "${jobs.fixedDelay}")
  public void getTask1() {
    System.out.println("任务1,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date()));
  }

  @Scheduled(cron = "${jobs.cron}")
  public void getTask2() {
    System.out.println("任务2,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date()));
  }
}

application.properties

jobs.fixedDelay=5000
jobs.cron=0/5 * *  * * ?

Application.java

package com.jege.spring.boot;

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

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:spring boot 启动类
 */

@SpringBootApplication
@EnableScheduling
public class Application {

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

}

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!
微信打赏
支付宝打赏

原文地址:https://www.cnblogs.com/je-ge/p/6126779.html