Home > Back-end >  How to run a method a the required number of times in spring boot?
How to run a method a the required number of times in spring boot?

Time:09-17

I'm learning RabbitMq and simply want to send message required number of times. I have Sender class that sends message to exchange, and I want to repeat it certain times. I'm using scheduled annotation, but It has different purpose, and don't match to me because it doesn't stop.

@Scheduled(initialDelay = 1000,fixedDelay = 1500)
    public void sendNumbers(){
        int index = atomicInteger.getAndIncrement();
        UUID uuid = uuids.get(index);
        Pair<Integer,Integer> pair = sumPair.get(uuid);
        MessagePostProcessor messagePostProcessor = message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setCorrelationId(uuid.toString());
            messageProperties.setReplyTo(response.getName());
            return message;
        };
        rabbitTemplate.convertAndSend(directExchange.getName(),routingKey,pair,messagePostProcessor);
    }

How can I do it?

CodePudding user response:

Just use a for loop to repeat the number of times you want.

You can do it in an ApplicationRunner.

@Bean
ApplicationRunner runner(RabbitTemplate template) {
    return () -> {
        for (int i = 0; i < 10; i  ) {
            ...
            template.convertAndSend(...)
        }
    };
  • Related