【SpringBoot】调度和执行定时任务--Spring Task(超详细)

Spring 提供了强大的任务调度功能,可以方便地在 Spring 应用中执行定时任务。Spring Task 是 Spring 框架中的一个模块,用于调度任务。它通过注解和 XML 配置两种方式来实现任务调度。

1. Spring Task 的基本用法

1.1 添加依赖

首先,在你的项目中添加 Spring Task 的依赖。如果你使用的是 Maven,可以在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.21</version> <!-- 请根据你的 Spring 版本进行调整 -->
</dependency>

1.2 启用任务调度

在 Spring Boot 应用中,可以通过在主类或配置类上添加 @EnableScheduling 注解来启用任务调度:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

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

1.3 定义定时任务

使用 @Scheduled 注解定义定时任务。@Scheduled 注解可以放在任何 Spring 管理的 bean 的方法上。以下是几种常用的调度方式:

  • fixedRate: 固定速率执行任务。
  • fixedDelay: 固定延迟执行任务。
  • cron: 使用 Cron 表达式执行任务。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("Current Time: " + System.currentTimeMillis());
    }

    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTimeWithDelay() {
        System.out.println("Current Time with Delay: " + System.currentTimeMillis());
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void reportCurrentTimeUsingCron() {
        System.out.println("Current Time using Cron: " + System.currentTimeMillis());
    }
}

2. Cron 表达式

Cron 表达式用于定义任务调度的时间规则。它由6或7个字段组成,字段之间用空格分隔。以下是每个字段的含义:

┌───────────── 秒 (0 - 59)
│ ┌───────────── 分 (0 - 59)
│ │ ┌───────────── 小时 (0 - 23)
│ │ │ ┌───────────── 日 (1 - 31)
│ │ │ │ ┌───────────── 月 (1 - 12)
│ │ │ │ │ ┌───────────── 星期几 (0 - 7) (0 和 7 都是星期日)
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *

2.1 特殊字符

  • *: 表示任意值。
  • ?: 仅在日和星期字段中使用,表示不指定值。
  • -: 表示范围,例如 10-12 表示从10到12。
  • ,: 表示列表值,例如 1,2,3 表示1、2、3。
  • /: 表示增量,例如 0/15 表示从0开始每15分钟。
  • L: 表示最后,例如 L 在日字段表示月的最后一天。
  • W: 表示最近的工作日,例如 15W 表示最接近15号的工作日。
  • #: 表示第几个星期几,例如 2#1 表示第一个星期一。

2.2 示例

  • 0 0 12 * * ?: 每天中午12点执行。
  • 0 15 10 ? * *: 每天上午10:15执行。
  • 0 15 10 * * ?: 每天上午10:15执行。
  • 0 15 10 * * ? 2024: 2024年每天上午10:15执行。
  • 0 * 14 * * ?: 每天下午2点到2:59每分钟执行一次。
  • 0 0/5 14 * * ?: 每天下午2点到2:55每5分钟执行一次。
  • 0 0/5 14,18 * * ?: 每天下午2点到2:55每5分钟执行一次,以及每天下午6点到6:55每5分钟执行一次。
  • 0 0-5 14 * * ?: 每天下午2点到2:05每分钟执行一次。
  • 0 10,44 14 ? 3 WED: 每年三月的每个星期三下午2:10和2:44执行。

通过这些基本用法和 Cron 表达式的介绍,你可以在 Spring 应用中方便地实现各种定时任务。根据具体需求选择适合的调度方式和时间规则。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值