Class IndexedDelay

  • All Implemented Interfaces:
    Delay

    public class IndexedDelay
    extends Object
    implements Delay
    A index based implementation of Delay. By being configurable through an injected function, callers can implement customs backoff algorithms.
    
     import ratpack.exec.ExecResult;
     import ratpack.exec.Promise;
     import ratpack.exec.util.retry.AttemptRetryPolicy;
     import ratpack.exec.util.retry.RetryPolicy;
     import ratpack.exec.util.retry.IndexedDelay;
     import ratpack.test.exec.ExecHarness;
    
     import java.time.Duration;
     import java.util.Arrays;
     import java.util.LinkedList;
     import java.util.List;
     import java.util.concurrent.atomic.AtomicInteger;
    
     import static org.junit.jupiter.api.Assertions.assertEquals;
    
     public class Example {
       private static final List<String> LOG = new LinkedList<>();
    
       public static void main(String... args) throws Exception {
         AtomicInteger source = new AtomicInteger();
    
         RetryPolicy retryPolicy = AttemptRetryPolicy.of(b -> b
           .delay(IndexedDelay.of(i -> Duration.ofMillis(500).multipliedBy(i)))
           .maxAttempts(3));
    
         ExecResult<Integer> result = ExecHarness.yieldSingle(exec ->
           Promise.sync(source::incrementAndGet)
             .mapIf(i -> i < 3, i -> { throw new IllegalStateException(); })
             .retry(retryPolicy, (i, t) -> LOG.add("retry attempt: " + i))
         );
    
         assertEquals(Integer.valueOf(3), result.getValue());
         assertEquals(Arrays.asList("retry attempt: 1", "retry attempt: 2"), LOG);
       }
     }
     
    Since:
    1.7
    • Method Detail

      • of

        public static IndexedDelay of​(Function<? super Integer,​Duration> indexedDelay)
        Builds an index based delay.
        Parameters:
        indexedDelay - a function expecting a retry attempt and returning the delay duration
        Returns:
        an indexed delay
      • delay

        public Promise<Duration> delay​(Integer attempt)
        Builds a promise wrapping a duration that will instruct the caller how long to wait between retries.
        Specified by:
        delay in interface Delay
        Parameters:
        attempt - current retry attempt to provide sophisticated delay strategies
        Returns:
        a promise wrapping a duration that will instruct the caller how long to wait between retries.