user5447339
user5447339

Reputation:

Using guava retry framework to keep retrying at fixed interval of time

I am using Guava retry in one of my project. I want to keep retrying at fixed interval if my method doesn't return true. As soon as it returns true, it should get stopped.

  public static void main(String[] args) {
    Callable<Boolean> callable = new Callable<Boolean>() {
      public Boolean call() throws Exception {
        System.out.println("hello: " + new Date());
        boolean status = false;
        return status;
      }
    };

    Retryer<Boolean> retryer =
        RetryerBuilder.<Boolean>newBuilder().retryIfResult(Predicates.<Boolean>alwaysTrue())
            .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.MINUTES))
            .withStopStrategy(StopStrategies.neverStop()).build();
    try {
      boolean abc = retryer.call(callable);
      System.out.println("world" + abc);
    } catch (RetryException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
  }

I have got the above code and it keeps retrying every one minute. Now if at runtime, I change the value of status to true, then it should get stopped but it didn't got stopped. Any idea what's wrong I am doing?

Upvotes: 1

Views: 8967

Answers (2)

yangyangli
yangyangli

Reputation: 1

You could modify here:

RetryerBuilder.<Boolean>newBuilder().retryIfResult(Predicates.<Boolean>.equalTo(true))

and then when the result changes to false, the retry will stop.

Upvotes: 0

eg04lt3r
eg04lt3r

Reputation: 2610

You are using wrong predicate. Your predicate always return 'true' and ignoring test your result from retry. Provide proper predicate:

Predicate<Boolean> predicate = new Predicate<Boolean>() {
        @Override
        public boolean apply(Boolean input) {
            return !input;
        }
    };
RetryerBuilder.<Boolean>newBuilder().retryIfResult(predicate)

Upvotes: 2

Related Questions