mercredi 15 mars 2023

How to implement retry mechanism using boolean flag in an elegant way

What I want to do:

I want to implement a retry mechanism for function checkExpiryForADate. There is one part within function checkExpiryForADate 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)

I have changed checkExpiryForADate to be like this to implement the retry mechanism

What I have tried:

@Scheduled(cron = "${scheduler: */10 7-8 * * MON-FRI}")
public void loadAndCheckExpiry() {
  boolean checkedRecordIsAvailable = false; //initialise the flag as false
  if (!checkedRecordIsAvailable) { //if flag is false, run `checkExpiryForADate`
      checkedRecordIsAvailable = checkExpiryForADate(dateService.today()); //update flag's value
  }
}

public boolean checkExpiryForADate(LocalDate asOf)
{
    Collection<Product> listOfProducts = productService.getProducts(asOf)

    for (Product product : listOfProducts) {

        //What I want to do here is that: if 1 of the products couldn't get `expiryRecord` in the `checkExpiry` function, 
        then we return false for the this `checkExpiryForADate` function

        if (!checkExpiry(product, asOf) {
            //get out of the for loop
            return false;
        }
    }

private boolean checkExpiry(Product product, LocalDate asOf) {
    //code to perform some operations - omitted

    List<Pair<ZonedDateTime, Double>> expiryRecords = new ArrayList<>(externalService.getRecord());
    if (expiryRecords.isEmpty()) {
        return false;
    }
    
    //code to perform some operations - omitted
    return true;
}

The problem with my code:

  1. In the loadAndCheckExpiry function, whenever the function is being run, checkedRecordIsAvailable will be initialised to false again. Is it that I should put the flag outside of the loadAndCheckExpiry? If so, it could be updated to true between 7-8AM (the schedule) - but I need to set it to false again everyday for the next day.
  2. In general, I think my code is very cumbersome, I wonder if there is any more elegant way to do it?

Any help would be greatly appreciated, thanks in advance.

Aucun commentaire:

Enregistrer un commentaire