在Spring Boot项目中使用@Scheduled注解实现定时任务

2022-10-28 14:08:34

在java开发中定时任务的实现有多种方式,jdk有自己的定时任务实现方式,很多框架也有定时任务的实现方式。这里,我介绍一种很简单的实现方式,在Spring Boot项目中使用两个注解即可实现。

在spring boot的启动类上面添加 @EnableScheduling 注解

image

新创建一个类,用来实现定时任务,这个类要注册为Bean才行,所以要加上 @Component 、@Repository 、 @ Controller 、@Service 、@Configration其中的一个注解。然后再里面的方法中加上 @Scheduled 注解。

image

然后为Scheduled注解加上属性,启动项目,就可以了。下面介绍Scheduled属性的用法。

fixedRate

fixedRate表示上一个执行开始后再一次执行的时间,但是必须要等上一次执行完成后才能执行。如果上一次执行完成了,还没到下一次执行的时间 ,就会等到下一次执行的时间到了才会执行,如果下一次的执行时间到了,上一次还没执行完,那么就会等到 上一次执行完成才会执行下一次。=后面的值 1000 为1秒。

@Scheduled(fixedRate = 1000)
public void fixedRate() throws Exception {
 System.out.println("fixedRate开始执行时间:" + new Date(System.currentTimeMillis()));
 //休眠8秒
 Thread.sleep(1000 * 8);
 System.out.println("fixedRate执行结束时间:" + new Date(System.currentTimeMillis()));
}

我们启动项目看看这个定时任务的执行情况,可以看到开始和结束时间之间间隔了8秒,然后马上执行了下一次。

image

我们把改成每2秒执行一次,休眠一秒,再来看看效果,可以看到开始执行的时间间隔了2秒。

@Scheduled(fixedRate = 1000 * 2)
public void fixedRate() throws Exception {
 System.out.println("fixedRate开始执行时间:" + new Date(System.currentTimeMillis()));
 //休眠8秒
 Thread.sleep(1000);
 System.out.println("fixedRate执行结束时间:" + new Date(System.currentTimeMillis()));
}

image

fixedDelay

fixedDelay表示上一次执行结束后再一次执行的时间,启动项目,可以看到上一次执行结束后还等了1秒才执行下一次。

@Scheduled(fixedDelay = 1000)
public void fixedDelay() throws Exception {
 System.out.println("fixedDelay开始执行时间:" + new Date(System.currentTimeMillis()));
 //休眠两秒
 Thread.sleep(1000 * 2);
 System.out.println("fixedDelay执行结束时间:" + new Date(System.currentTimeMillis()));
}

image

initialDelay

initialDelay表示项目启动后延迟多久执行定时任务,所以他要配合fixedRate或fixedDelay一起使用。

@Scheduled(initialDelay = 1000*3, fixedDelay = 1000)
public void initialDelay() throws Exception {
 System.out.println("initialDelay开始执行时间:" + new Date(System.currentTimeMillis()));
}

启动项目,可以看到项目启动完成后,等了3秒才开始执行的定时任务。

image

ceon

cron是一种表达式,具体的写法规格有兴趣的可以去学习一下,不懂也不影响使用,直接按照示例就可以类推,写出自己想要的,也可以直接使用在线生成。

image

下面写几个示例:

*/3 * * * * ? 每隔3秒执行一次

0 */1 * * * ? 每隔1分钟执行一次

0 0 3-10 * * ? 每天3-10点整点触发

0 0/3 * * * ? 每三分钟触发一次

0 0-3 14 * * ? 在每天下午2点到下午2:03期间的每1分钟触发

0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发

0 0 10,14,17 * * ? 每天上午10点,下午2点,5点

cron大致了解后,来看看实现效果,我写的是每 3秒执行一次

@Scheduled(cron = "*/3 * * * * ?")
public void cron() {
 System.out.println("cron开始执行时间:" + new Date(System.currentTimeMillis()));
}

启动项目后,可以看到每次的执行时间间隔了3秒

image

spring boot 用@Scheduled注解实现定时任务就介绍到这里。

项目源码地址

  • 作者:戴草帽的长虫
  • 原文链接:https://blog.csdn.net/qq_40068922/article/details/102945531
    更新时间:2022-10-28 14:08:34