main
1using System;
2using System.Collections.Generic;
3using System.Timers;
4
5namespace gorilla.commons.infrastructure.threading
6{
7 public interface ITimer
8 {
9 void start_notifying(ITimerClient client_to_be_notified, TimeSpan span);
10 void stop_notifying(ITimerClient client_to_stop_notifying);
11 }
12
13 public class IntervalTimer : ITimer
14 {
15 readonly ITimerFactory factory;
16 readonly IDictionary<ITimerClient, Timer> timers;
17
18 public IntervalTimer() : this(new TimerFactory())
19 {
20 }
21
22 public IntervalTimer(ITimerFactory factory)
23 {
24 this.factory = factory;
25 timers = new Dictionary<ITimerClient, Timer>();
26 }
27
28 public void start_notifying(ITimerClient client_to_be_notified, TimeSpan span)
29 {
30 stop_notifying(client_to_be_notified);
31
32 var timer = factory.create_for(span);
33 timer.Elapsed += (sender, args) =>
34 {
35 client_to_be_notified.notify();
36 };
37 timer.Start();
38 timers[client_to_be_notified] = timer;
39 }
40
41 public void stop_notifying(ITimerClient client_to_stop_notifying)
42 {
43 if (!timers.ContainsKey(client_to_stop_notifying)) return;
44 timers[client_to_stop_notifying].Stop();
45 timers[client_to_stop_notifying].Dispose();
46 }
47 }
48}