-
Notifications
You must be signed in to change notification settings - Fork 0
/
Retry.cs
89 lines (76 loc) · 2.31 KB
/
Retry.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Diagnostics;
namespace ClassLibrary1
{
public static class Retry
{
public static void Until(Action stuffToRetry, Func<bool> stopWhenTrue, TimeSpan? timeToRetry = null)
{
var internalTimeToRetry = timeToRetry ?? 5.Seconds();
var startTime = DateTime.Now;
Func<bool> timeSinceStart = () => DateTime.Now - startTime > internalTimeToRetry;
var timeIsUp = timeSinceStart();
do
{
timeIsUp = timeSinceStart();
stuffToRetry();
} while (!timeIsUp && !stopWhenTrue());
}
}
public class Tests
{
public void IfTrueRightAway()
{
var timesTried = 0;
Retry.Until(() => timesTried++, () => true);
Debug.Assert(timesTried == 1);
}
public void IfTrueAfterOneSecondAway()
{
Debug.Assert(TryFor(10.Milliseconds()) >= 1);
}
public void IfNeverTrue()
{
var startTime = DateTime.Now;
var timesTried = TryFor(10.Seconds());
var elapsedTime = DateTime.Now - startTime;
Console.WriteLine(elapsedTime);
Debug.Assert(elapsedTime < 5500.Milliseconds());
Debug.Assert(timesTried > 1);
}
private static int TryFor(TimeSpan timeSpan)
{
var timesTried = 0;
var startTime = DateTime.Now;
Retry.Until(() => timesTried++, () => DateTime.Now - startTime > timeSpan);
Console.WriteLine(timesTried);
return timesTried;
}
}
}
namespace System
{
public static class TimeSpanExtensions
{
public static TimeSpan Seconds(this int length)
{
return TimeSpan.FromSeconds(length);
}
public static TimeSpan Minutes(this int length)
{
return TimeSpan.FromMinutes(length);
}
public static TimeSpan Milliseconds(this int length)
{
return TimeSpan.FromMilliseconds(length);
}
public static TimeSpan Days(this int length)
{
return TimeSpan.FromDays(length);
}
public static TimeSpan Hours(this int length)
{
return TimeSpan.FromHours(length);
}
}
}