Infinite retries for calling external service

Hello,

I am implementing a process which calls an external service and my model currently uses a Service Task. Is there a way to set retries to infinite so if the external service is down, we retry until it is back up?

From what I have read, I should use an External Task, but I could not find an example how to implement it for such a case, when it is not really an External task, but rather a Service Task which calls an external service. If someone could send such an example or provide hints, that would be great.

Thank you!

Hello my friend:

Below I leave an example of how to implement an external task with logic to handle retries and the external task timeout time.

In the getRetries() method you can adjust so that the retries are always the same when they fall into the “catch”, without decreasing this number.

But this is just one of the ways you can do it, you can implement the logic however you want to be used in catch.

@Component
@ExternalTaskSubscription("send-mail")
public class MailSendHandler implements ExternalTaskHandler {
   private static final Logger log = LoggerFactory.getLogger(MailSendHandler.class);
   private static final long ONE_MINUTE = 1000L * 60;
   private static final int MAX_RETRIES = 5;
   private final MailService mailService;

   public MailSendHandler(final MailService mailService) {
      this.mailService = mailService;
   }

   public void execute(ExternalTask task, ExternalTaskService taskService) {
      try {
          // obtain variables from process-context
          String recipient = task.getVariable("recipient");
          String content = task.getVariable("content");

          // send mail
          this.mailService.send(recipient, content);
         
          // complete, if successful
          taskService.complete(task);

      } catch (Exception e) {
          log.error("{}: {}", e.getClass().getSimpleName(), e.getMessage(), e);
          Integer retries = this.getRetries(task);
          Long timeout = this.getNextTimeout(retries);
          taskService.handleFailure(
             task, e.getMessage(), 
             ExceptionUtils.getStackTrace(e), 
             retries, timeout);
      }
   }

   private Integer getRetries(ExternalTask task) {
      Integer retries = task.getRetries();
      if (retries == null) {
          retries = MAX_RETRIES;
      } else {
          retries = retries - 1;
      }
      return retries;
   }

   private Long getNextTimeout(Integer retries) {
      // increasing interval: 1 additional minute delay after each retry
      return ONE_MINUTE * (MAX_RETRIES - retries);
   }
}

I hope this helps!

William Robert Alves