Spring Boot应用程序定期运行方法

3 java spring spring-boot

我正在使用一个简单的 Spring Boot 应用程序和 RabbitMQ。

但是我不知道如何定期运行一个方法。

这是我的应用程序类

@SpringBootApplication
public class SampleApp {
    @Autowired
    Sender sender;

    public static void main(String[] args) {
        SpringApplication.run(SampleApp.class, args);
    }

    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        sender.sendMessage();
    }
}
Run Code Online (Sandbox Code Playgroud)

sendMessage方法定义如下

@Scheduled(fixedRate = 3000L)
public void sendMessage() {
    log.info("Sending message...");
    rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", "TEST MESSAGE");
}
Run Code Online (Sandbox Code Playgroud)

然而这个方法只被调用一次,我只能在控制台中看到一行。

我的代码中遗漏了什么?

谢谢。

cas*_*lin 5

看起来你失踪了@EnableScheduling:

@EnableScheduling
@SpringBootApplication
public class SampleApp {
    ...
}
Run Code Online (Sandbox Code Playgroud)

引用文档:

启用 Spring 的计划任务执行功能,类似于 Spring 的<task:*>XML 命名空间中的功能。用于@Configuration类如下:

@EnableScheduling
@SpringBootApplication
public class SampleApp {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这使得能够检测@Scheduled容器中任何 Spring 管理的 bean 上的注释。