springboot定时任务
在 Spring Boot 中,定时任务是通过注解和配置轻松实现的。Spring Boot 提供了多种定时任务实现方式,最常见的是使用 @Scheduled
注解来配置定时任务。以下是 Spring Boot 中实现定时任务的几种方式及其使用方法。
1. 使用 @Scheduled 注解实现定时任务
@Scheduled
是 Spring 框架中用于声明定时任务的方法级别注解。通过在方法上添加该注解,你可以指定任务执行的时间间隔或执行时间。常见的几种方式有:固定频率执行、固定延迟执行以及使用 cron 表达式。
a. 基本配置
在 Spring Boot 中启用定时任务,只需要在主类或配置类上添加 @EnableScheduling
注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableScheduling
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}
b. @Scheduled 使用示例
- 固定速率执行任务(Fixed Rate)
@Scheduled(fixedRate = X)
:每隔X
毫秒执行一次任务,任务开始时计算时间间隔,忽略任务执行所花的时间。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;@Component
public class FixedRateTask {@Scheduled(fixedRate = 5000) // 每5秒执行一次public void performTask() {System.out.println("Fixed rate task executed at " + System.currentTimeMillis());}
}
- 固定延迟执行任务(Fixed Delay)
@Scheduled(fixedDelay = X)
:任务执行完成后,再等待X
毫秒后再执行下一次任务。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;</