使用@Scheduled实现定时任务
在Spring Boot中,通过@Scheduled注解可以快速实现定时任务功能。以下是具体实现方式和相关配置说明。
基本配置方法
创建一个带有@Component注解的类,在需要定时执行的方法上添加@Scheduled注解。同时需要在主配置类上添加@EnableScheduling注解启用定时任务功能。
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void taskWithFixedRate() {
System.out.println("Fixed Rate Task: " + System.currentTimeMillis());
}
}
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
常用调度属性
@Scheduled注解支持多种调度方式:
java
@Scheduled(fixedRate = 5000) // 固定速率执行
@Scheduled(fixedDelay = 3000) // 固定延迟执行
@Scheduled(cron = "0 15 10 * * ?") // Cron表达式
时区支持
通过 zone 参数指定时区,例如:
@Scheduled(cron = "0 0 12 * * ?", zone = "GMT+8") 表示北京时间12:00执行
时间间隔执行方式
固定速率执行是指上一次开始执行时间点之后固定时间间隔执行:
java
@Scheduled(fixedRate = 60000) // 每分钟执行一次
固定延迟执行是指上一次执行结束时间点之后固定时间间隔执行:
java
@Scheduled(fixedDelay = 30000) // 上次执行完成后30秒再执行
初始延迟配置
可以设置首次执行的延迟时间:
java
@Scheduled(initialDelay = 10000, fixedRate = 60000) // 启动10秒后开始,之后每分钟执行
Cron表达式规则
Cron表达式包含6-7个字段(秒 分 时 日 月 周 年):
java
@Scheduled(cron = "0 0 9 * * ?") // 每天9点执行
@Scheduled(cron = "0 0/5 14,18 * * ?") // 每天14点和18点,每隔5分钟执行
@Scheduled(cron = "0 15 10 ? * MON-FRI") // 工作日10:15执行