Spring Boot中实现定时任务最常用的方法 @Scheduled 注解和 TaskScheduler 接口【包含详情代码】

Spring Boot中实现定时任务最常用的方法 @Scheduled 注解和 TaskScheduler 接口【包含详情代码】

学习总结

1、掌握 JAVA入门到进阶知识(持续写作中……
2、学会Oracle数据库入门到入土用法(创作中……
3、手把手教你开发炫酷的vbs脚本制作(完善中……
4、牛逼哄哄的 IDEA编程利器技巧(编写中……
5、面经吐血整理的 面试技巧(更新中……

在这里插入图片描述
其中最常用的是使用 @Scheduled 注解和 TaskScheduler 接口。以下是如何在 Spring Boot 应用程序中实现定时任务的步骤:

1. 添加依赖

首先,确保你的 Spring Boot 项目中包含了 spring-boot-starterspring-boot-starter-web 依赖。如果你使用的是 Maven,可以在 pom.xml 文件中添加如下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. 启用定时任务

在 Spring Boot 应用程序的配置类或主类上添加 @EnableScheduling 注解,以启用定时任务功能。

@SpringBootApplication
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

3. 创建定时任务

创建一个类,并在该类中的方法上使用 @Scheduled 注解来定义定时任务。

@Component
public class MyScheduledTasks {
    @Scheduled(fixedRate = 5000) // 每5秒执行一次
    public void performTask() {
        System.out.println("执行定时任务: " + new Date());
    }
}

@Scheduled 注解支持多种属性,包括:

  • fixedRate:固定速率执行,单位是毫秒。
  • fixedDelay:固定延迟执行,单位是毫秒。
  • cron:使用 Cron 表达式来定义执行计划。

4. 使用 Cron 表达式

如果你需要更复杂的执行计划,可以使用 Cron 表达式。

@Component
public class MyScheduledTasks {
    @Scheduled(cron = "0 0 * * * ?") // 每小时执行一次
    public void performTask() {
        System.out.println("执行定时任务: " + new Date());
    }
}

5. 配置 TaskScheduler

如果你需要自定义 TaskScheduler 的属性,可以在 application.propertiesapplication.yml 文件中配置。

spring.task.scheduling.pool.size=10 # 线程池大小
spring.task.scheduling.thread-name-prefix=MyScheduler- # 线程名称前缀

6. 测试定时任务

启动 Spring Boot 应用程序,你将看到定时任务按照配置的计划执行。
通过以上步骤,你可以在 Spring Boot 应用程序中实现基本的定时任务。如果你需要更高级的定时任务管理,可以考虑使用 Quartz Scheduler,它是一个功能更强大的作业调度库,也可以与 Spring Boot 集成使用。

往期文章

 第一章:日常_JAVA_面试题集(含答案)
 第二章:日常_JAVA_面试题集(含答案)
平安壹钱包JAVA面试官:请你说一下Mybatis的实现原理
Java必备面试-热点-热门问题精华核心总结-推荐
 往期文章大全……
在这里插入图片描述

一键三连 一键三连 一键三连~

更多内容,点这里❤

  • 31
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值