原文: https://howtodoinjava.com/spring-boot/enable-scheduling-scheduled-job-example/

为了使 Spring Boot 应用程序中的作业定期运行,Spring Boot 提供了@EnableScheduling@Scheduled注解。 让我们学习如何使用 Spring boot @Scheduled 注解。

假设您要每隔 10 秒运行一次作业。 您可以通过以下步骤实现此作业调度:

1. 将@EnableScheduling添加到SpringBootApplication

在您的 Spring Boot 应用程序类中添加@EnableScheduling注解。 @EnableScheduling是一个 Spring 上下文模块注解。 它通过@Import(SchedulingConfiguration.class)指令在内部导入SchedulingConfiguration

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class SpringBootWebApplication {
  4. }

阅读更多:在 Spring 中安排任务的 4 种方法

2. 将 Spring boot @Scheduled注解添加到方法中

现在,您可以在要调度的方法上添加@Scheduled注解。 唯一的条件是方法应没有参数

导入的SchedulingConfiguration将创建的ScheduledAnnotationBeanPostProcessor将扫描所有已声明的 bean,以查看是否存在@Scheduled注解。

对于每个没有参数的带注解的方法,将创建适当的执行程序线程池。 该线程池将管理带注解的方法的调度调用。

2.1. 以固定速率安排任务

在固定的速率执行任务:

  1. @Scheduled(initialDelay = 1000, fixedRate = 10000)
  2. public void run() {
  3. logger.info("Current time is :: " + Calendar.getInstance().getTime());
  4. }

现在,在控制台中观察输出:

  1. 2017-03-08 15:02:55 - Current time is :: Wed Mar 08 15:02:55 IST 2017
  2. 2017-03-08 15:03:05 - Current time is :: Wed Mar 08 15:03:05 IST 2017
  3. 2017-03-08 15:03:15 - Current time is :: Wed Mar 08 15:03:15 IST 2017
  4. 2017-03-08 15:03:25 - Current time is :: Wed Mar 08 15:03:25 IST 2017
  5. 2017-03-08 15:03:35 - Current time is :: Wed Mar 08 15:03:35 IST 2017

2.2. 固定延迟安排任务

将任务配置为在固定延迟后运行。 在给定的示例中,上一次执行的结束与下一次执行的开始之间的持续时间是固定的。 该任务始终等待直到上一个任务完成。

  1. @Scheduled(fixedDelay = 10000)
  2. public void run() {
  3. logger.info("Current time is :: " + Calendar.getInstance().getTime());
  4. }

2.3. Spring Boot Cron 工作示例

@Scheduled注解非常灵活,也可以采用 cron 表达式

  1. @Scheduled(cron = "0 10 10 10 * ?")
  2. public void run() {
  3. logger.info("Current time is :: " + Calendar.getInstance().getTime());
  4. }

在这个 Spring 任务调度程序注解示例中,向我提出您的问题。

学习愉快!