-
Notifications
You must be signed in to change notification settings - Fork 3
/
AlarmClock.cs
66 lines (59 loc) · 2.03 KB
/
AlarmClock.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace ClassLibrary4
{
public class AlarmClock : Handles<Message>
{
readonly SortedSet<Messages.Timeout<Message>> alarms = new SortedSet<Messages.Timeout<Message>>(AlarmClockComparer.Instance);
readonly object alarmLock = new object();
private volatile bool stopped;
private readonly Thread workerThread;
class AlarmClockComparer : IComparer<Messages.Timeout<Message>>
{
public static readonly IComparer<Messages.Timeout<Message>> Instance = new AlarmClockComparer();
public int Compare(Messages.Timeout<Message> x, Messages.Timeout<Message> y)
{
return x.AlarmTime.CompareTo(y.AlarmTime);
}
}
public AlarmClock(IPublishEvents bus)
{
workerThread = new Thread(
_ =>
{
while (!stopped)
{
lock (alarmLock)
{
var now = DateTime.UtcNow;
var shouldSend = alarms.Where(x => x.AlarmTime > now).ToList();
foreach (var alarm in shouldSend)
{
bus.Publish(alarm.Message);
alarms.Remove(alarm);
}
}
Thread.Sleep(1);
}
});
}
public void Start()
{
workerThread.Start();
}
public void Stop()
{
stopped = true;
}
public void Handle(Message message)
{
var alarmTime = DateTime.UtcNow.AddSeconds(30);
lock (alarmLock)
{
alarms.Add(new Messages.Timeout<Message>(message, alarmTime));
}
}
}
}