@Schedule中关于fixedDelay和fixedRate的区别
先介绍下Schedule的使⽤⽅法
1.⾸先新建使⽤Springboot的Maven项⽬,引⼊相关引⽤如下在l⾥添加如下:<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
2.新建MySchedule的Java⽂件,⽤@Component来注释该类,定时任务⽤@Scheduled来注释如下:
@Scheduled(fixedRate=2000)
public void fixedRate(){
System.out.println("fixedRate:"+new Date());
}
该代码会定时2秒钟执⾏⼀次在这⾥插⼊代码⽚,执⾏结果如下
文成公主真实历史绿色出行手抄报但是@Scheduled中还有⼀种属性fixedDelay,两者有什么区别,区别就是如果执⾏任务中有阻塞的情况,fixedDelay执⾏间隔会加上阻塞的时间代码如下:
@Scheduled(fixedDelay=2000)
public void fixedDelay(){
try
{
Thread.currentThread().sleep(1000);//毫秒
爱英文>借代和借喻的区别}
catch(Exception e){}
System.out.println("fixedDelay:"+new Date());
}
科学抗疫
执⾏结果如下
可以看出后⼀次执⾏的时间是fixedDelay的时间加阻塞时间;
⽽fixedRate则是按其规定的时间来执⾏的,犹如时刻表⼀般,当阻塞结束后按时刻表来执⾏,代码如下:
@Scheduled(fixedRate=2000)德与得
public void fixedRate(){
try
{说说心里话作文
Thread.currentThread().sleep(1000);//毫秒
}
catch(Exception e){}
System.out.println("fixedRate:"+new Date());
}
执⾏结果如下
香菇功效图中可以看到,执⾏结果中时间间隔为fixedRate定的时间间隔
总结来说,fixedRate下⼀次执⾏时间是本次开始时间加间隔时间;⽽fixedDelay下⼀次执⾏时间是本次结束时间加间隔时间