在spring boot中,可以使用@scheduled注解快速的实现一些常用的定时任务场景,接下来讲解具体的实现方式。
package com.zwwhnly.springbootdemo; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.scheduling.annotation.enablescheduling; @enablescheduling @springbootapplication public class springbootdemoapplication { public static void main(string[] args) { springapplication.run(springbootdemoapplication.class, args); } }
package com.zwwhnly.springbootdemo; import org.springframework.scheduling.annotation.scheduled; import org.springframework.stereotype.component; import java.text.simpledateformat; import java.util.date; @component public class testschedule { private simpledateformat simpledateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss"); // 每5秒执行一次 @scheduled(fixedrate = 5000) public void testfixedrate() { system.out.println("当前时间:" + simpledateformat.format(new date())); } }
运行结果如下图所示:
以上场景中每次任务的执行时间不会超过定义的频率(5秒),因此从运行结果看执行很正常,那么在实际的业务场景中,任务的执行时间是可能会超过定义的频率的,彼时程序又是如何运行的呢?
我们来修改下代码,让其每次都延迟6秒:
// 每5秒执行一次 @scheduled(fixedrate = 5000) public void testfixedrate() { system.out.println("当前时间:" + simpledateformat.format(new date())); try { thread.sleep(6000); } catch (interruptedexception e) { e.printstacktrace(); } }
此时的运行结果为:
从结果可以看出,如果任务的执行时间超过了定义的频率,那么上一次任务执行完后,会立即执行下一次任务。
除了上面的fixeddelay,@scheduled还支持fixdelay和cron表达式。
我们先来看下fixeddelay的使用:
// 上次任务执行结束时间与下次任务执行开始的间隔时间为5s @scheduled(fixeddelay = 5000) public void testfixeddelay() { system.out.println("当前时间:" + simpledateformat.format(new date())); try { thread.sleep(6000); } catch (interruptedexception e) { e.printstacktrace(); } }
从运行结果可以看出,每两次打印的时间间隔为11秒,也就是任务执行完成后(6s),又延迟了5秒才开始执行下一次任务。
通过这个示例也能比较出fixedrate与fixeddelay的区别。
接下来我们来讲解下使用cron表达式来配置定时任务,在实际的场景中,该种方式使用的更多,因为它配置很灵活,可以满足很多种场景,如每隔多久执行,某个固定的时间点执行等。
// 每20秒执行一次 @scheduled(cron = "0/20 * * * * ? ") public void testfixeddelay() { system.out.println("当前时间:" + simpledateformat.format(new date())); }
更多的cron表达式,可以到网站去自定义,满足你的各种场景。
参考文章:
springboot使用@scheduled做定时任务,以及连接池问题
如对本文有疑问, 点击进行留言回复!!
详解SpringBoot修改启动端口server.port的四种方式
网友评论