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