-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConditionalTimer.cs
49 lines (42 loc) · 1.21 KB
/
ConditionalTimer.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
using System;
using System.Timers;
namespace.MyTimers.Utils.Timer
{
public class ConditionalTimer
{
private System.Timers.Timer internalTimer;
private readonly Action action;
private readonly Func<bool> stopCondition;
private readonly int interval;
public ConditionalTimer(Action action, Func<bool> stopCondition, int interval)
{
this.action = action;
this.stopCondition = stopCondition;
this.interval = interval;
SetUpTimer();
}
private void SetUpTimer()
{
internalTimer = new System.Timers.Timer(interval) {AutoReset = false};
internalTimer.Elapsed += new ElapsedEventHandler(Target);
}
public void ExecuteTimer()
{
internalTimer.Start();
}
private void Target(object sender, ElapsedEventArgs elapsedEventArgs)
{
internalTimer.Stop();
action();
var shouldContinue = !stopCondition();
if (shouldContinue)
{
internalTimer.Start();
}
else
{
internalTimer.Dispose();
}
}
}
}