forked from microsoft/coyote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathControlledTimer.cs
72 lines (64 loc) · 1.95 KB
/
ControlledTimer.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Coyote.Samples.CoffeeMachineTasks
{
/// <summary>
/// This class provides a Timer that is similar to how the Actor model timers work that
/// has delays that can be controlled by Coyote tester.
/// </summary>
internal class ControlledTimer
{
private readonly CancellationTokenSource Source = new CancellationTokenSource();
private readonly TimeSpan StartDelay;
private readonly TimeSpan? Interval;
private readonly Action Handler;
private bool Stopped;
private readonly string Name;
public ControlledTimer(string name, TimeSpan startDelay, TimeSpan interval, Action handler)
{
this.Name = name;
this.StartDelay = startDelay;
this.Interval = interval;
this.Handler = handler;
this.StartTimer(startDelay);
}
public ControlledTimer(string name, TimeSpan dueTime, Action handler)
{
this.Name = name;
this.StartDelay = dueTime;
this.Handler = handler;
this.StartTimer(dueTime);
}
private void StartTimer(TimeSpan dueTime)
{
Task.Run(async () =>
{
await Task.Delay(dueTime, this.Source.Token);
this.OnTick();
});
}
private void OnTick()
{
if (!this.Stopped)
{
this.Handler();
if (this.Interval.HasValue)
{
this.StartTimer(this.Interval.Value);
}
}
}
public void Stop()
{
this.Stopped = true;
this.Source.Cancel();
}
public override string ToString()
{
return this.Name;
}
}
}