Spring Boot 实现定时任务的案例

以下是一个使用 Spring Boot 实现定时任务的案例,涵盖了定时任务的基本配置和实现。

案例:定时发送邮件提醒

  1. 添加依赖

在 pom.xml 中添加 Spring Boot 的依赖,以及邮件发送的相关依赖:

XML 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</dependencies>
  1. 配置定时任务

在 Spring Boot 的主类上启用定时任务:

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling // 启用定时任务
public class ScheduledTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTaskApplication.class, args);
    }
}
  1. 创建定时任务类

创建一个定时任务类,定义定时任务的方法:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class EmailReminderTask {

    @Autowired
    private JavaMailSender mailSender;

    // 定义定时任务,每天早上 9 点执行
    @Scheduled(cron = "0 0 9 * * ?")
    public void sendDailyReminder() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo("[email protected]");
        message.setSubject("每日提醒");
        message.setText("这是您的每日提醒邮件,今天是 " + new Date());
        
        mailSender.send(message);
        System.out.println("每日提醒邮件已发送!");
    }
}
  1. 配置邮件属性

在 application.properties 文件中配置邮件发送的相关属性:

bash 复制代码
spring.mail.host=smtp.example.com
spring.mail.port=587
[email protected]
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
  1. 测试运行

启动 Spring Boot 应用程序,定时任务会自动开始运行。每天早上 9 点,系统会自动发送一封提醒邮件。

扩展案例:动态调整定时任务

如果需要动态调整定时任务的执行时间,可以通过以下方式实现:

  1. 创建配置类

创建一个配置类,用于存储定时任务的配置信息:

java 复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "task.schedule")
public class TaskScheduleConfig {
    private String cronExpression;

    public String getCronExpression() {
        return cronExpression;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }
}
  1. 修改定时任务类

在定时任务类中注入配置类,并使用 @Scheduled 注解的 cron 属性动态设置执行时间:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class DynamicTask {

    @Autowired
    private TaskScheduleConfig taskScheduleConfig;

    // 动态设置定时任务的执行时间
    @Scheduled(cron = "#{taskScheduleConfig.cronExpression}")
    public void executeTask() {
        System.out.println("动态定时任务执行中...");
        // 任务逻辑
    }
}
  1. 配置属性文件

在 application.properties 文件中添加定时任务的配置:

bash 复制代码
task.schedule.cronExpression=0 0/5 * * * ?

以上配置表示每 5 分钟执行一次任务。

注意事项

  1. 任务线程池:默认情况下,Spring Boot 的定时任务使用单线程顺序执行。如果需要并发执行多个任务,可以配置任务线程池。

  2. 任务监控:可以结合 Spring Boot Actuator 对定时任务进行监控和管理。

  3. 任务异常处理:在任务中添加异常处理逻辑,避免任务因异常而停止执行。

  4. 任务日志:记录任务的执行日志,方便后续的排查和分析。

通过以上案例,你可以快速实现 Spring Boot 中的定时任务功能,并根据实际需求进行扩展和优化。

相关推荐
懵逼的小黑子3 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
小林学习编程4 小时前
SpringBoot校园失物招领信息平台
java·spring boot·后端
愿你天黑有灯下雨有伞4 小时前
Spring Boot整合Kafka实战指南:从环境搭建到消息处理全解析
spring boot·kafka·linq
Clf丶忆笙5 小时前
SpringBoot异步处理@Async深度解析:从基础到高阶实战
spring boot
java1234_小锋6 小时前
Spring Bean有哪几种配置方式?
java·后端·spring
柯南二号7 小时前
【后端】SpringBoot用CORS解决无法跨域访问的问题
java·spring boot·后端
每天一个秃顶小技巧8 小时前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
帮帮志8 小时前
vue实现与后台springboot传递数据【传值/取值 Axios 】
前端·vue.js·spring boot
gCode Teacher 格码致知9 小时前
《Asp.net Mvc 网站开发》复习试题
后端·asp.net·mvc
杨不易呀10 小时前
Java面试高阶篇:Spring Boot+Quarkus+Redis高并发架构设计与性能优化实战
spring boot·redis·高并发·分布式锁·java面试·quarkus