基于Spring的任务调度器完成Spring Boot定时任务

Spring Boot定时任务使用注解驱动的方式,通过在需要执行的方法上添加@Scheduled注解,并指定任务的触发时间和频率,Spring就会在指定的时间间隔内自动调用该方法。Spring Boot定时任务支持多种触发方式,例如固定延迟、固定频率、cron表达式等。可以用于各种场景,如定时备份数据、定时发送邮件等。

1、pom.xml 文件中添加以下依赖项:

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-scheduling</artifactId>  
</dependency>

2、使用 @Scheduled 注解实现定时任务:
1)、固定延迟(Fixed Delay):

import org.springframework.scheduling.annotation.Scheduled;  
import org.springframework.stereotype.Component;  
  
@Component  
public class ScheduledTasks {  
  
    @Scheduled(fixedDelay = 86400000) // 每天凌晨2点执行(2小时后)  
    public void performTask() {  
        // 在这里添加您的任务逻辑  
    }  
}

2)、固定频率(Fixed Rate):

import org.springframework.scheduling.annotation.Scheduled;  
import org.springframework.stereotype.Component;  
  
@Component  
public class ScheduledTasks {  
  
    @Scheduled(fixedRate = 86400000) // 每天凌晨2点执行(2小时后)  
    public void performTask() {  
        // 在这里添加您的任务逻辑  
    }  
}

3)、cron 表达式(Cron Expression):

import org.springframework.scheduling.annotation.Scheduled;  
import org.springframework.stereotype.Component;  
  
@Component  
public class ScheduledTasks {  
  
    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行  
    public void reportCurrentTime() {  
        System.out.println("Current time is " + new java.util.Date());  
    }  
}

cron 表达式是用于定义时间规则的一种字符串格式,它包含了秒、分钟、小时、天、月、星期等六个字段。每个字段都表示一个时间单位,并且使用一个特定的符号来表示该字段的取值范围。
cron 表达式 0 0 2 * * ? 表示每天凌晨2点执行该方法。

  • 0 表示秒数,使用0表示每一分钟的第0秒。
  • 0 表示分钟数,使用0表示每一小时的第0分钟。
  • 2 表示小时数,使用2表示每天的第2小时(凌晨2点)。
  • * 表示日期,使用*表示每一天。
  • * 表示月份,使用*表示每个月。
  • ? 表示星期几,使用?表示不指定星期几。

3、在配置类上添加 @EnableScheduling 注解:

import org.springframework.context.annotation.Configuration;  
import org.springframework.scheduling.annotation.EnableScheduling;  
  
@Configuration  
@EnableScheduling  
public class AppConfig {  
    // ...其他配置项...  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值