Spring ScheduledTasks不触发

时间:2019-10-13 08:18:55

标签: 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的类)

为什么会这样?如何让计划方法在添加它们的任何类中运行?

1 个答案:

答案 0 :(得分:2)

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

@Component
@EnableScheduling
public MySchdeduleClass {

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