Spring ScheduledTasks 未触发 [英] Spring ScheduledTasks not firing

查看:40
本文介绍了Spring ScheduledTasks 未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ");
  }

但该方法从未运行,我注意到如果我将该方法移动到 Spring Boot Application 类(承载 main 的类)

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?

推荐答案

您必须将 @EnableScheduling 注释添加到您的一个 Spring 配置类中或包含您的方法的另一个类之上,以便例子:

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 ");
      }
}

这篇关于Spring ScheduledTasks 未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆