Spring Boot定时任务

定时任务

在开发中,我们经常会用到定时任务的功能,例如定时同步数据,定时发送邮件等等,Spring Boot也提供了定时任务的功能

基本使用

要使用定时任务,首先需要开启项目的定时任务功能,只需要在启动类或者配置类中添加@EnableScheduling注解

@EnableScheduling
@SpringBootApplication
public class SpringDemoApplication {

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

}

创建一个定时任务类,使用@Component注解添加到Spring容器中,然后在组件中创建定时执行方法,在方法上标注@Scheduled注解,使用cron表达式指定定时任务执行的时间,例如以下示例在每分钟的第0秒执行一次

@Slf4j
@Component
public class MyTask {

    @Scheduled(cron = "0 * * * * ?")
    public void printTask() {
        log.info("触发定时任务");
    }

}

启动项目,定时任务在每分钟都会执行一次

在这里插入图片描述

corn表达式

@Scheduled注解使用corn表达式来表示定时任务执行的时间,要让定时任务在期望的时候执行,首先需要清楚corn表达式的表示方法

corn表达式由7位组成,分别表示秒/分/时/日/月/星期/年,但是@Scheduled注解中的corn表达式之支持前6位

corn表达式支持通配符,常用的通配符如下:

  • *:在每个位上来表示所有值,例如*** * * * * ?**表示每一秒都执行
  • ?:在日期位上或者星期位上来表示不设置,在设置了日期后,星期就可以使用?来表示,反之亦然
  • -:表示范围,例如0 5-20 * * * ?,表示从第5分钟到20分钟每分钟触发一次
  • /:表示从指定起始时间开始,每隔固定时间触发一次,例如0 5/20 * * * ?,表示第5,25,45分钟分别触发一次
  • ,:表示列出枚举值,例如0 5,20 * * * ?,表示在5分钟和20分钟各触发一次

关于corn表达式还有很多表示方式,具体可以查询网上相关资料,或者使用一些在线corn表达式翻译工具

关于corn表达式还有很多表示方式,具体可以查询网上相关资料,或者使用一些在线corn表达式翻译工具

在这里插入图片描述

### 如何在 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."); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值