-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEngine.cs
More file actions
117 lines (106 loc) · 2.61 KB
/
Engine.cs
File metadata and controls
117 lines (106 loc) · 2.61 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.Threading;
using System.Threading.Tasks;
using SyncWhole.Common;
using SyncWhole.Logging;
namespace SyncWhole
{
public sealed class Engine
{
private readonly object _stateLock = new object();
private readonly Timer _timer;
private TimeSpan _timerInterval = TimeSpan.FromMinutes(15);
private bool _paused;
private CalendarSynchronizer _synchronizer;
public bool SyncInProcess { get; private set; }
public bool Ready => _synchronizer != null && !SyncInProcess && !_paused;
public DateTime? NextSync { get; private set; }
public Engine()
{
_timer = new Timer(OnTimer);
_paused = true;
}
public void SetUpSync(IAppointmentSourceFactory source, IAppointmentDestinationFactory destination, TimeSpan interval)
{
lock (_stateLock)
{
if (!_paused)
{
throw new InvalidOperationException("Cannot set up until paused");
}
_synchronizer = new CalendarSynchronizer(source, destination);
_timerInterval = interval;
Logger.Info($"Scheduled synchronization from {_synchronizer.SourceName} to {_synchronizer.DestinationName} every {interval}");
}
}
public void Pause()
{
lock (_stateLock)
{
_paused = true;
RewindTimer();
Logger.Verbose("Synchronization paused");
}
}
public void Resume()
{
lock (_stateLock)
{
if (!_paused)
{
return;
}
_paused = false;
if (Ready)
{
RewindTimer();
Logger.Verbose("Synchronization resumed");
}
}
}
private void RewindTimer()
{
_timer.Change(_paused ? Timeout.InfiniteTimeSpan : _timerInterval, Timeout.InfiniteTimeSpan);
NextSync = _paused ? (DateTime?)null : DateTime.Now.Add(_timerInterval);
}
private async void OnTimer(object state)
{
lock (_stateLock)
{
if (!Ready)
{
RewindTimer();
return;
}
NextSync = null;
}
await SyncAsync(false).ConfigureAwait(false);
lock (_stateLock)
{
RewindTimer();
}
}
public async Task SyncAsync(bool force)
{
if (!Ready)
{
return;
}
try
{
SyncInProcess = true;
Logger.Info($"Synchronization started...");
var statistics = await _synchronizer.SynchronizeAsync(force).ConfigureAwait(false);
Logger.Info($"Synchronization successful. {statistics.Created} new events created, {statistics.Deleted} old events deleted, {statistics.Updated} events updated");
}
catch (Exception ex)
{
Logger.Exception("Synchronization failed", ex);
}
finally
{
SyncInProcess = false;
}
}
}
}