Springboot 定时任务 @EnableScheduling @Scheduled

`@EnableScheduling` 是Spring框架中的一个注解,它用于开启基于注解的任务调度支持。当你在你的Spring应用程序中使用这个注解时,它允许你通过`@Scheduled`注解来配置和执行定时任务。

以下是如何使用 `@EnableScheduling` 的基本步骤:

1. **添加@EnableScheduling注解**:
   在你的Spring Boot启动类或者配置类上添加`@EnableScheduling`注解,以开启定时任务的支持。
   ```java
   import org.springframework.scheduling.annotation.EnableScheduling;
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;

   @SpringBootApplication
   @EnableScheduling
   public class Application {

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

2. **创建定时任务方法**:
   在你的组件中创建方法,并使用`@Scheduled`注解来配置任务的执行计划。
   `&#

### 如何在 Spring Boot 中使用 `@Scheduled` 注解实现定时任务 #### 配置主类或配置类 为了启用定时任务功能,在 Spring Boot 的主应用程序类或者某个配置类上需要添加 `@EnableScheduling` 注解。这一步是必不可少的,因为该注解会激活 Spring 容器内的调度机制[^2]。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling // 启用定时任务功能 public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` --- #### 创建定时任务方法 创建一个普通的组件类(通过 `@Component` 或其他类似的注解标记),并在其中定义带有 `@Scheduled` 注解的方法。此注解用于指定任务执行的时间间隔或其他触发条件[^3]。 以下是几种常见的定时任务设置方式: 1. **基于固定时间间隔的任务** 可以使用 `fixedRate` 属性来设定每次任务之间的最小间隔时间(单位为毫秒)。 ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) // 每隔 5 秒运行一次 public void fixedRateTask() { System.out.println("Fixed Rate Task executed at: " + System.currentTimeMillis()); } } ``` 2. **基于延迟时间间隔的任务** 如果希望当前任务完成后等待一段时间再启动下一个任务,则可以使用 `fixedDelay` 属性。 ```java @Scheduled(fixedDelay = 10000) // 当前任务结束后等待 10 秒再运行下一次 public void fixedDelayTask() { System.out.println("Fixed Delay Task executed at: " + System.currentTimeMillis()); } ``` 3. **基于 Cron 表达式的复杂任务计划** 对于更复杂的场景,比如每天凌晨两点执行某项操作,可以通过 `cron` 属性提供自定义表达式。 ```java @Scheduled(cron = "0 0/5 * * * ?") // 每五分钟运行一次 public void cronTask() { System.out.println("Cron Task executed at: " + System.currentTimeMillis()); } @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨两点运行一次 public void dailyCronTask() { System.out.println("Daily Cron Task executed at: " + System.currentTimeMillis()); } ``` --- #### 注意事项 - 默认情况下,`@Scheduled` 基于单线程池工作。如果多个任务可能重叠或耗时较长,建议调整线程池大小以提高并发能力。 - 若要修改默认行为,可以在配置文件中加入如下属性: ```properties spring.task.scheduling.pool.size=5 # 设置线程池大小为 5 ``` - 时间计算均基于 JVM 所在服务器的本地时区。因此需注意部署环境与时区的一致性问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值