spring 的 scheduled 定时任务的使用
在 Spring 中,@Scheduled 注解用于定义和管理定时任务。这个注解可以标记在方法上,使其能够按指定的时间间隔或固定的计划触发执行。以下是 @Scheduled 注解的使用方法和配置方式:
1. 启用定时任务支持
在 Spring Boot 项目中,首先需要启用定时任务支持,可以在主应用类上添加 @EnableScheduling 注解:
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);
}
}
2. 使用 @Scheduled 注解
@Scheduled 注解支持多种配置方式,可以根据需要选择适合的方式定义任务的执行频率。
a) fixedRate:按固定速率执行任务
-
fixedRate指定一个以毫秒为单位的固定速率。无论上一次执行是否完成,都会在固定间隔时间触发任务。import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) // 每隔5秒执行一次 public void executeTask() { System.out.println("Task executed at fixed rate of 5 seconds"); } }
b) fixedDelay:按固定延迟执行任务
-
fixedDelay指定任务在上一次执行完成后,等待一定的延迟(毫秒)再开始下一次执行。@Scheduled(fixedDelay = 5000) // 上次任务执行完成后等待5秒再执行 public void executeTaskWithFixedDelay() { System.out.println("Task executed with fixed delay of 5 seconds after the last task completion"); }
c) initialDelay:设置初始延迟
-
initialDelay用于在应用启动后,延迟指定时间(毫秒)再执行任务。通常结合fixedRate或fixedDelay使用。@Scheduled(fixedRate = 5000, initialDelay = 10000) // 应用启动后延迟10秒首次执行 public void executeTaskWithInitialDelay() { System.out.println("Task executed after initial delay of 10 seconds and every 5 seconds thereafter"); }
d) cron 表达式:按 Cron 表达式定义任务计划
-
cron参数支持 Cron 表达式,可用更灵活的方式指定任务的执行时间。Cron 表达式的格式如下:秒 分 时 日 月 周 [年]例如:
@Scheduled(cron = "0 0 * * * ?") // 每小时整点执行 public void executeTaskWithCronExpression() { System.out.println("Task executed at the start of every hour"); }
3. Cron 表达式示例
"0 0 * * * ?":每小时的整点执行"0 0 12 * * ?":每天中午12点执行"0 0 0 * * ?":每天午夜0点执行"*/10 * * * * ?":每10秒执行一次"0 0/5 * * * ?":每5分钟执行一次
4. 异常处理
-
默认情况下,
@Scheduled任务在遇到异常时会停止执行。可以通过try-catch语句捕获异常,确保任务不会中断:@Scheduled(fixedRate = 5000) public void executeTaskWithExceptionHandling() { try { // 任务逻辑 } catch (Exception e) { // 异常处理逻辑 } }
总结
- 使用
@Scheduled可以轻松地创建定时任务,选择fixedRate、fixedDelay或cron表达式来灵活控制任务的执行频率。 - 启用定时任务时,记得加上
@EnableScheduling注解。 - 根据需要处理异常,确保任务能够持续稳定运行。
注意:在分布式场景中,需要保证对于某一次任务只有在其中一个服务器节点上被执行,不能多个节点执行同一个定时任务,
具体方案有:
浙公网安备 33010602011771号