Spring ScheduledTasks not firing

谁说胖子不能爱 提交于 2019-12-11 16:23:17

问题


I'm trying to run a method in Spring with ScheduledTasks, so I have the following class:

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() {
    }
}

And the following method in a different class

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

But the method never runs, I've noticed thought that if I move the method to the Spring Boot Application class (the class that hosts main)

Why is this happening? How I can get schedule methods to run in wherever class that I add them?


回答1:


You have to add the @EnableScheduling annotation in one of your Spring configuration classes or above the other class that contains your method, for example:

@Component
@EnableScheduling
public MySchdeduleClass {

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


来源:https://stackoverflow.com/questions/58361755/spring-scheduledtasks-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!