从零开始 Spring Boot 40:定时任务

本文介绍了如何在SpringBoot中配置和使用定时任务,包括fixedDelay和fixedRate的区别,以及如何通过cron表达式设置特定时间执行。文章还探讨了并发执行定时任务的方法,并展示了如何动态调整任务延迟和自定义TaskScheduler以实现多线程并发执行。
摘要由CSDN通过智能技术生成

从零开始 Spring Boot 40:定时任务

spring boot

图源:简书 (jianshu.com)

定时任务是一种很常见的需求,比如我们可能需要应用定期去执行一些清理工作,再比如可能需要定期检查一些外部服务的可用性等。

fixedDelay

要在 Spring 中开启定时任务相关功能,需要在任意的配置类上添加上@EnableScheduling

@Configuration
@EnableScheduling
public class WebConfig {
   
}

之后就可以在 Spring Bean 中定义一个定时任务对应的方法:

@Component
public class MySchedule {
   
    @Scheduled(fixedDelay = 1000)
    public void sayHello() {
   
        LocalDateTime now = LocalDateTime.now();
        System.out.println("hello, now is %s".formatted(now));
    }
}

在这个示例中,@Scheduled(fixedDelay = 1000)表示所标记的方法将每隔1000毫秒(1秒)执行一次。fixedDelay中的值代表下一次任务将在前一次任务执行完毕后的若干毫秒后执行。

所以这个示例执行后能看到类似下面的输出:

hello, now is 2023-06-14T15:27:21.026108300
hello, now is 2023-06-14T15:27:22.034320100
hello, now is 2023-06-14T15:27:23.038852900
hello, now is 2023-06-14T15:27:24.054180300
hello, now is 2023-06-14T15:27:25.065741600

要注意的是,定时任务对应的方法返回值必须是void,且不能包含任何参数。

fixedRate

除了上边介绍的方式外,还可以指定“每间隔若干时间后执行定时任务”这种模式:

@Component
public class MySchedule {
   
    @Scheduled(fixedRate = 1000)
    public void sayHello() {
   
        LocalDateTime now = LocalDateTime.now();
        System.out.println("hello, now is %s".formatted(now));
    }
}

@ScheduledfixedRate属性可以设置每次任务执行间隔的毫米数。

fixedDelay vs fixedRate

fixedDelayfixedRate是有区别的,虽然上面的两个例子输出看起来一样,但这是因为任务执行的时间太短造成的,我们将任务执行的时间放长:

@Component
public class MySchedule {
   
    @Scheduled(fixedDelay = 1000)
    public void sayHello() throws InterruptedException {
   
        LocalDateTime now = LocalDateTime.now();
        System.out.println("hello, now is %s".formatted(now));
        Thread.sleep(2000);
    }
}

输出:

hello, now 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值