Gojo
Gojo

Reputation: 169

Best way to delay a call an external API via Java Spring Boot?

So I have a java app that calls 2 APIs.

  1. Call an API to get a request a file to be generated
  2. Call the second API to get the file.

The first API returns the credentials to get the file. The Second one returns the file but it may take a few seconds or minutes to be generated. What is the best way to account for the time delay between asking the file to be generated and the file being available to pull? Some retry logic should be necessary but on the initial call it always returns a 4xx HTTP response. What's the best way to make this api call maybe there's a better way than using RestTemplate to sequentially call the 2 apis? I thought of adding a short time delay before the 2nd call but I was wondering if there is a better library or async method I can use that's more efficient. I'd appreciate any 2 cents thanks!

Upvotes: 0

Views: 1451

Answers (1)

will
will

Reputation: 61

If the author of these two apis is a partner of yours, I think there's a better way, like, the file generator call a callback api of yours and then you call the second API to get the file. And as a supplement, considering unexpected exceptions during above process, a retry schedule to fetch the missed file is probably necessary.

But if you just want to implement the retry and async code more gracefully, the following is my idea

//call the first API

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
CompletableFuture<File> completionFuture = new CompletableFuture<>();

final ScheduledFuture<?> checkFuture = executor.scheduleAtFixedRate(() -> {
  //Call the second API to get the file
  //if("have got the file successfully") {
  //    completionFuture.complete(the file);
  //} else {
  //    //do nothing
  //}
}, 5, 1, TimeUnit.SECONDS);//set a reasonable schedule policy

completionFuture.whenComplete((file, thrown) -> {
  //do something when the retry schedule complete
  checkFuture.cancel(false);
});

completionFuture.orTimeout(10, TimeUnit.SECONDS);//setting a timeout policy is probably necessary

Upvotes: 1

Related Questions