mercredi 15 mars 2023

How to implement retry mechanism with exception and try catch

What I want to do:

I want to implement a retry mechanism for function dailyComputeValue. dailyComputeValue will call computeValue. There is one part within function ComputeValue where we will call externalService.getRecord, which could return an empty list.

If this is the case, I want to rerun the function every 10 min until it does not return an empty list (Once externalService.getRecord does not return an empty list when we run checkExpiryForADate, we would not run it anymore within the scheduled timeframe (from 7AM to 9AM)

The complication is that I cannot use a boolean flag in this case because computeValue needs to return a double. So I am thinking of throwing an exception if externalService.getRecord returns an empty list. I have changed dailyComputeValue to be like the code below to implement the retry mechanism

What I have tried:

@Scheduled(cron = "${scheduler: */10 7-8 * * MON-FRI}")
public void dailyComputeValue() {
  double value = 0;
  try {
      value = computeValue(String product);
  } 
  catch {
     log.warn("Record not available yet", ex.getMessage();)
  }
  //to only save to database if there is good value (not from the empty list)
  valueRepository.save(value);
}

public Double computeValue(String product)
{
    List<Pair<ZonedDateTime, Double>> valueRecords = new ArrayList<>(externalService.getRecord());
    if (valueRecords.isEmpty()){
    throw new Exception("Record not available yet");
    }
    //perform some operation to return a double
}

The problem with my code:

The current code will retry computeValue every 10 minutes, but will not stop once computeValue returns a double. I am not sure how to implement the code to "rerun the function every 10 min until it does not return an empty list (Once externalService.getRecord does not return an empty list when we run dailyComputeValue, we would not run it anymore within the scheduled timeframe (from 7AM to 9AM)".

Any help would be greatly appreciated, thanks in advance.

Aucun commentaire:

Enregistrer un commentaire