aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Threading/PeriodicTimer.cs
blob: 057a84483b58b3e729d5d1a4988e68f3f398dd00 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Threading;
using Microsoft.Win32;

namespace MediaBrowser.Server.Implementations.Threading
{
    public class PeriodicTimer : IDisposable
    {
        public Action<object> Callback { get; set; }
        private Timer _timer;
        private readonly object _state;
        private readonly object _timerLock = new object();
        private readonly TimeSpan _period;

        public PeriodicTimer(Action<object> callback, object state, TimeSpan dueTime, TimeSpan period)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            Callback = callback;
            _period = period;
            _state = state;

            StartTimer(dueTime);
        }

        void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            if (e.Mode == PowerModes.Resume)
            {
                DisposeTimer();
                StartTimer(Timeout.InfiniteTimeSpan);
            }
        }

        private void TimerCallback(object state)
        {
            Callback(state);
        }

        private void StartTimer(TimeSpan dueTime)
        {
            lock (_timerLock)
            {
                _timer = new Timer(TimerCallback, _state, dueTime, _period);

                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
            }
        }

        private void DisposeTimer()
        {
            SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
            
            lock (_timerLock)
            {
                if (_timer != null)
                {
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }

        public void Dispose()
        {
            DisposeTimer();
        }
    }
}