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

标签 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();
    }
}

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/

相关文章:

java - 在简单示例项目中更改 Spring 框架日志级别?

spring-boot - Spring Boot 插件不会在 jar 中添加 lib 文件夹

java - 使用 CentOS 6 安装 highcharts 服务器

java - 由 : org. hibernate.QueryException 引起:无法解析内部枚举类的属性

java - 使用 jakarta.* 包在 Tomcat 10.x 上部署 Spring 5.x

java - 从 Spring Boot 中的基本身份验证中删除 WWW-authenticate header

spring - 在Hibernate实体中使用aspectj

java - 如何正确使用 setPriority() 方法?

java - ESAPI 编码器规范化更改查询参数

hibernate - 记录 Java Web 应用程序中的实体更改