summaryrefslogtreecommitdiff
path: root/lib/infrastructure/threading/IntervalTimer.cs
blob: 74f3055845f4aad07318e3a076e70070495af814 (plain)
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
using System;
using System.Collections.Generic;
using jive.utility;

namespace jive.infrastructure.threading
{
  public class IntervalTimer : Timer
  {
    readonly ITimerFactory factory;
    readonly IDictionary<TimerClient, System.Timers.Timer> timers;

    public IntervalTimer() : this(new TimerFactory())
    {
    }

    public IntervalTimer(ITimerFactory factory)
    {
      this.factory = factory;
      timers = new Dictionary<TimerClient, System.Timers.Timer>();
    }

    public void start_notifying(TimerClient client_to_be_notified, TimeSpan span)
    {
      stop_notifying(client_to_be_notified);

      var timer = factory.create_for(span);
      timer.Elapsed += (o, e) =>
      {
        client_to_be_notified.notify();
      };
      timer.Start();
      timers[client_to_be_notified] = timer;
    }

    public void stop_notifying(TimerClient client_to_stop_notifying)
    {
      if (!timers.ContainsKey(client_to_stop_notifying)) return;
      timers[client_to_stop_notifying].Stop();
      timers[client_to_stop_notifying].Dispose();
    }

    public void Dispose()
    {
      timers.each(x => x.Value.Dispose());
      timers.Clear();
    }
  }
}