spring boot @Scheduled 定时任务

@Scheduled中参数说明
@Scheduled(fixedRate=2000):上一次开始执行时间点后2秒再次执行;

@Scheduled(fixedDelay=2000):上一次执行完毕时间点后2秒再次执行;

@Scheduled(initialDelay=1000, fixedDelay=2000):第一次延迟1秒执行,然后在上一次执行完毕时间点后2秒再次执行;

@Scheduled(cron="* * * * * ?"):按cron规则执行。
注解中给定时间
@Component
public class ExampleTimer {

        /*每100秒执行一次*/
        @Scheduled(fixedRate = 100000)
        public void timerRate() {
            //do something....
        }

        /*第一次10秒后执行,当执行完后2秒再执行*/
        @Scheduled(initialDelay = 10000, fixedDelay = 2000)
        public void timerInit() {
                        //do something....
        }

        /*每天15:39:00时执行*/
        @Scheduled(cron = "0 39 15 * * ? ")
        public void timerCron() {
                        //do something....
        }
}
配置文件给定时间
@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 * *  * * ?

猜你喜欢

转载自blog.csdn.net/asd104/article/details/80772345