SpringBoot @Scheduled定时任务的fixedRate,fixedDelay,cron的作用和不同

649 阅读1分钟

一. 三种定时类型。

1.cron --@Scheduled(cron="0/6 * * * *?")

当时间达到设置的时间会触发事件。上面那个例子会每5秒执行一次。

  • 2018/1/4 14:27:30
  • 2018/1/4 14:27:36
  • 2018/1/4 14:27:42
  • 2018/1/4 14:27:48
  • 2018/1/4 14:27:56

2.fixedRate --@Scheduled(fixedRate=6000)

每六秒执行一次时间。

3.fixedDelay --@Scheduled(fixedDelay=2000)

每次任务执行完之后的2s后继续执行

看字面意思容易理解,但是任务执行长度超过周期会怎样呢?

不多说,直接上图:

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

@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {    
System.out.println("现在时间:" + dateFormat.format(new Date()));
}

private int count=0;

@Scheduled(cron="*/6 * * * * ?")
private void process(){    
System.out.println("this is scheduler task runing  "+(count++));
}

需要在类上加 @Component   启动类上加@EnableScheduling