问题
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