2016-01-29 03:40:21 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using Microsoft.Win32;
|
|
|
|
|
|
2016-11-03 22:53:02 +00:00
|
|
|
|
namespace MediaBrowser.Server.Startup.Common.Threading
|
2016-01-29 03:40:21 +00:00
|
|
|
|
{
|
|
|
|
|
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)
|
|
|
|
|
{
|
2016-01-29 03:42:03 +00:00
|
|
|
|
if (callback == null)
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("callback");
|
|
|
|
|
}
|
|
|
|
|
|
2016-01-29 03:40:21 +00:00
|
|
|
|
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);
|
|
|
|
|
|
2016-11-03 22:53:02 +00:00
|
|
|
|
Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
|
2016-01-29 03:40:21 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void DisposeTimer()
|
|
|
|
|
{
|
2016-11-03 22:53:02 +00:00
|
|
|
|
Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
|
2016-01-29 03:40:21 +00:00
|
|
|
|
|
|
|
|
|
lock (_timerLock)
|
|
|
|
|
{
|
|
|
|
|
if (_timer != null)
|
|
|
|
|
{
|
|
|
|
|
_timer.Dispose();
|
|
|
|
|
_timer = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
DisposeTimer();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|