java - Spring ScheduledTasks 未触发

标签 java spring spring-boot scheduled-tasks

我正在尝试使用 ScheduledTasks 在 Spring 中运行一个方法,因此我有以下类:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;

@Component
public class ScheduledTasks {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    public void scheduleTaskWithFixedRate() {
    }

    public void scheduleTaskWithFixedDelay() {
    }

    public void scheduleTaskWithInitialDelay() {
    }

    public void scheduleTaskWithCronExpression() {
    }
}

以及不同类中的以下方法

  @Scheduled(fixedRate = 10 * 1000) //10 seconds
  public void taskThatRunsPeridically() {
      logger.info("Scheduled task method has been called ");
  }

但是该方法永远不会运行,我注意到如果我将该方法移动到 Spring Boot Application 类(托管 main 的类)

为什么会发生这种情况?如何让计划方法在我添加它们的任何类中运行?

最佳答案

您必须在其中一个 Spring 配置类中或在包含您的方法的其他类之上添加 @EnableScheduling 注释,例如:

@Component
@EnableScheduling
public MySchdeduleClass {

      @Scheduled(fixedRate = 10 * 1000) //10 seconds
      public void taskThatRunsPeridically() {
          logger.info("Scheduled task method has been called ");
      }
}

关于java - Spring ScheduledTasks 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361755/

相关文章:

java - 在 ResourceSupport 中设置实体中不存在的表单字段的正确位置

spring - 在 Spring Cloud 配置客户端之间共享配置

java - 使用 {{ }} 创建对象和设置数据

java - 如何使用 Spring MVC Controller 返回 html 文件

java - 当调用构造函数时会发生什么(在这种情况下概念很清晰)?

java - 如何在 Spring Data 中延迟加载集合?

spring-boot - 将自定义 header 添加到 REST PUT 请求

rest - 如何将 MediaType 添加到 MappingJackson2HttpMessageConverter 而不是 RestTemplate

java - 将 HashMap 与文本文件进行比较

java - Spring REST api OAuth2 验证来自外部授权服务器的 token