Generate a random time interval between 4 and 8 hours long. Sometimes useful for adding jitter to periodic tasks, or staggering scheduled tasks for better load distribution.
// Generate a random time interval between 4 and 8 hours long
// https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
Random rnd = new Random();
int min = 240; // 4 hours
int max = 480; // 8 hours
var randomMinutes = Convert.ToInt32(rnd.Next(min, max));
var interval = TimeSpan.FromMinutes(randomMinutes);
Console.WriteLine(interval);
// 05:34:00
/// <summary>
/// Generates a random time period from the specified min/max minutes.
/// </summary>
/// <param name="min">The lower bound (inclusive) minutes.</param>
/// <param name="max">The upper bound (exclusive) minutes.</param>
/// <returns>A random TimeSpan between the specified min/max minutes.</returns>
/// <remarks>
/// This method is NOT thread-safe. See: https://andrewlock.net/building-a-thread-safe-random-implementation-for-dotnet-framework/
/// </remarks>
public static TimeSpan GenerateRandomMinutes(int min, int max)
{
var random = new Random();
var randomMinutes = Convert.ToInt32(random.Next(min, max));
return TimeSpan.FromMinutes(randomMinutes);
}