我正在使用一个简单的 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();
}
}
sendMessage方法定义如下
@Scheduled(fixedRate = 3000L)
public void sendMessage() {
log.info("Sending message...");
rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", "TEST MESSAGE");
}
但是这个方法只被调用一次,我在控制台中只能看到一行。
我的代码中遗漏了什么?
谢谢。
最佳答案
看起来您失踪了 @EnableScheduling
:
@EnableScheduling
@SpringBootApplication
public class SampleApp {
...
}
引用文档:
Enables Spring's scheduled task execution capability, similar to functionality found in Spring's
<task:*>
XML namespace. To be used on@Configuration
classes as follows:@Configuration @EnableScheduling public class AppConfig { // various @Bean definitions }
This enables detection of
@Scheduled
annotations on any Spring-managed bean in the container.
关于java - Spring Boot应用程序定期运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58372714/