Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot application run method periodically

I am playing with a simple Spring Boot application and RabbitMQ.

However I cannot figure out how to run a method periodically.

Here is my Application class

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

And the sendMessage method is defined as below

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

However this method is called only once, I can see only a single line in the console.

What I missed in my code?

Thanks.


1 Answers

Looks like you are missing @EnableScheduling:

@EnableScheduling
@SpringBootApplication
public class SampleApp {
    ...
}

Quoting the documentation:

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.

like image 60
cassiomolin Avatar answered Feb 02 '26 17:02

cassiomolin