Table of Contents

Building a Custom Schedule

Warning

Before building a custom Schedule consider using the existing components and build them up via composition

A custom Schedule needs four members.

  1. Extend from Schedule
  2. Implement the GetEnumerator method
  3. Implement CanCount
  4. Implement Count
Note

For Schedule that are infinite CanCount is false and Count is null

First, a Schedule that returns only odd natural numbers in seconds up to a provided max.


/// <summary>
/// <see cref="Schedule"/> that returns all the odd seconds up to <see cref="Max"/>
/// seconds
/// </summary>
/// <param name="Max">max seconds</param>
public sealed record OddSecondsToMax(uint Max) : Schedule
{
    public override int? Count => (int)Max;
    public override bool CanCount => true;

    public override IEnumerator<Duration> GetEnumerator()
    {
        for (int i = 1, j = 0; j < Max; i++)
        {
            if (i % 2 == 0)
            {
                continue;
            }

            j++;
            yield return TimeSpan.FromSeconds(i);
        }
    }
}

public static class OddSecondsToMaxTests
{
    [Fact(DisplayName = "returns all the odd seconds up to max seconds")]
    public static void Case1()
    {
        Schedule schedule = new OddSecondsToMax(10);

Duration
1 second
3 seconds
5 seconds
7 seconds
9 seconds
11 seconds
13 seconds
15 seconds
17 seconds
19 seconds

The logic is all within the GetEnumerator and yield and break make it trivial to build any Schedule.

For example here is the Polly.NET DecorrelatedJitterBackoffV2 as a Schedule


/// <summary>
/// Example <see cref="Schedule"/> with implementation copied from
/// https://github.com/App-vNext/Polly/blob/main/src/Polly.Core/Retry/RetryHelper.cs#L86C29-L86C56
/// </summary>
public sealed record DecorrelatedJitterBackoffV2(Duration BaseDelay, Func<double> Randomizer)
    : Schedule
{
    // A factor used within the formula to help smooth the first calculated delay.
    const double PFactor = 4.0;

    // A factor used to scale the median values of the retry times generated by
    // the formula to be _near_ whole seconds, to aid Polly user comprehension.
    // This factor allows the median values to fall approximately at 1, 2, 4 etc
    // seconds, instead of 1.4, 2.8, 5.6, 11.2.
    const double RpScalingFactor = 1 / 1.4d;

    const double ExponentialFactor = 2.0;

    public override int? Count => null;
    public override bool CanCount => false;

    public override IEnumerator<Duration> GetEnumerator()
    {
        double prev = 0;
        for (int attempt = 0; ; attempt++)
        {
            // Upper-bound to prevent overflow beyond TimeSpan.MaxValue.
            double maxTimeSpanDouble = (double)TimeSpan.MaxValue.Ticks - 1000;

            long targetTicksFirstDelay = ((TimeSpan)BaseDelay).Ticks;

            double t = attempt + Randomizer();
            double next = Math.Pow(ExponentialFactor, t) * Math.Tanh(Math.Sqrt(PFactor * t));

            double formulaIntrinsicValue = next - prev;
            prev = next;

            yield return TimeSpan.FromTicks(
                (long)
                    Math.Min(
                        formulaIntrinsicValue * RpScalingFactor * targetTicksFirstDelay,
                        maxTimeSpanDouble
                    )
            );
        }
    }
}

public static class DecorrelatedJitterBackoffV2Tests
{
    [Fact]
    public static void Case1()
    {
        Random seededRandom = new Random(123456);
        Schedule schedule = new DecorrelatedJitterBackoffV2(
            TimeSpan.FromSeconds(1),
            () => seededRandom.NextDouble()
        ).Take(10);

Duration
665 milliseconds
827 milliseconds
1 second, 403 milliseconds
4 seconds, 471 milliseconds
12 seconds, 935 milliseconds
11 seconds, 715 milliseconds
20 seconds, 259 milliseconds
1 minute, 7 seconds
2 minutes, 27 seconds
6 minutes, 13 seconds