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 {
// ...其他配置项...
}