Spring Boot定时任务

本文介绍如何在 Spring Boot 应用中实现定时任务。通过在启动类上添加 @EnableScheduling 注解来启用定时任务功能,并展示了使用 @Scheduled 注解创建一个每3秒执行一次的简单示例。


1、在启动类前面加上@EnableScheduling开启定时任务功能

2、编写定时任务,代码如下:

@Component
public class MyScheduled {
    @Scheduled(fixedRate = 3000)//单位是毫秒
    public void schedule1() {
        System.out.println("xxxxx");
    }
}


### 如何在 Spring Boot 中实现定时任务 #### 启用定时任务支持 为了使定时任务功能生效,在主类或配置类上添加 `@EnableScheduling` 注解来开启调度服务的支持[^1]。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class ScheduledTasksApplication { public static void main(String[] args) { SpringApplication.run(ScheduledTasksApplication.class, args); } } ``` #### 创建定时方法 定义业务逻辑并使用 `@Scheduled` 来标注那些计划要周期性运行的方法。可以指定固定延迟(`fixedDelay`)、固定速率(`fixedRate`)或是cron表达式的执行模式[^2]。 ##### 使用固定的延时参数 当上次调用完成后等待一定时间再启动下一次: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class FixedDelayTask { @Scheduled(fixedDelay = 5000) public void reportCurrentTime() { System.out.println("Fixed delay task - " + new java.util.Date()); } } ``` ##### 利用Cron表达式自定义触发规则 对于更复杂的场景,比如每天凌晨两点钟执行,则可以通过设置 cron 属性完成此需求: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class CronTriggeredTask { // Runs every day at midnight. @Scheduled(cron = "0 0 * * * ?") public void executeDailyMidnightJob(){ System.out.println("Executing daily job at midnight"); } // Runs on the first minute of every hour (e.g., 9:01 AM). @Scheduled(cron="0 1 * * * ?") public void hourlyJobExample(){ System.out.println("This will run once an hour."); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值