-
Notifications
You must be signed in to change notification settings - Fork 19
/
BackgroundTasks.cs
238 lines (205 loc) · 7.93 KB
/
BackgroundTasks.cs
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
namespace RoliSoft.TVShowTracker
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;
/// <summary>
/// Periodically runs tasks asynchronously in the background.
/// </summary>
public static class BackgroundTasks
{
/// <summary>
/// Gets or sets the task timer.
/// </summary>
/// <value>The task timer.</value>
public static Timer TaskTimer { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the background tasks are currently being run.
/// </summary>
/// <value>
/// <c>true</c> if the background tasks are currently being run; otherwise, <c>false</c>.
/// </value>
public static bool InProgress { get; set; }
private static DateTime _lastSoftwareUpdate = Utils.UnixEpoch;
private static int _inProgressCount = 0;
private static long _lastMemUse = 0;
private static Thread _lastThd;
/// <summary>
/// Initializes the <see cref="BackgroundTasks"/> class.
/// </summary>
static BackgroundTasks()
{
TaskTimer = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds);
TaskTimer.Elapsed += Tasks;
}
/// <summary>
/// Initializes this instance.
/// </summary>
public static void Start()
{
Log.Debug("Starting background tasks timer...");
TaskTimer.Start();
}
/// <summary>
/// The tasks which will run periodically.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param>
public static void Tasks(object sender = null, ElapsedEventArgs e = null)
{
if (InProgress)
{
if (_inProgressCount == 5)
{
Log.Warn("It is time to run Tasks(), but the last one didn't finish yet. Thread will be killed and a new Tasks() will run. (6/6)");
try
{
_lastThd.Abort();
_lastThd = null;
}
catch (Exception ex)
{
Log.Debug("Exception on stuck Tasks() thread abort.", ex);
}
}
else
{
Log.Warn("It is time to run Tasks(), but the last one didn't finish yet so it'll be dropped. (" + (_inProgressCount + 1) + "/6)");
_inProgressCount++;
return;
}
}
_lastThd = Thread.CurrentThread;
var st = DateTime.Now;
Log.Debug("Running background tasks...");
InProgress = true;
_inProgressCount = 0;
try
{
Library.StartWatching();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while reindexing the library during background tasks.", ex);
}
try
{
CheckSoftwareUpdate();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while checking for software update during background tasks.", ex);
}
try
{
CheckDatabaseUpdate();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while checking for database update during background tasks.", ex);
}
try
{
CheckShowListUpdate();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while checking for show list update during background tasks.", ex);
}
try
{
ProcessMonitor.CheckOpenFiles();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while checking for open files during background tasks.", ex);
}
try
{
//AutoDownloader.SearchForMissingEpisodes();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while searching for missing episodes during background tasks.", ex);
}
try
{
RestartIfNeeded();
}
catch (Exception ex)
{
Log.Error("Unhandled exception while checking if a software restart is required during background tasks.", ex);
}
InProgress = false;
Log.Debug("Background tasks completed in " + (DateTime.Now - st).TotalSeconds + "s.");
}
/// <summary>
/// Checks if a new version is available from the software.
/// </summary>
public static void CheckSoftwareUpdate()
{
if ((DateTime.Now - _lastSoftwareUpdate).TotalHours > 0.5)
{
_lastSoftwareUpdate = DateTime.Now;
MainWindow.Active.CheckForUpdate();
}
}
/// <summary>
/// Checks if update is required and runs it if it is.
/// </summary>
public static void CheckDatabaseUpdate()
{
var ts = DateTime.Now - (Database.Setting("update") ?? "0").ToDouble().GetUnixTimestamp();
if (ts.TotalHours > 10 && !Updater.InProgress)
{
Log.Debug("The database was last updated " + ts.TotalHours + " hours ago, starting new update.");
MainWindow.Active.Run(() => MainWindow.Active.UpdateDatabaseClick());
}
}
/// <summary>
/// Checks if the list of known TV shows is older than a day.
/// </summary>
public static void CheckShowListUpdate()
{
var fn = Path.Combine(Signature.InstallPath, @"misc\tvshows");
var ts1 = DateTime.Now - File.GetLastWriteTime(fn);
if (ts1.TotalDays > 1)
{
Log.Debug("The known TV show names were last updated " + ts1.TotalHours + " hours ago, downloading new list.");
FileNames.Parser.GetAllKnownTVShows();
}
var fn2 = Path.Combine(Signature.InstallPath, @"misc\linkchecker");
var ts2 = DateTime.Now - File.GetLastWriteTime(fn2);
if (ts2.TotalDays > 1)
{
Log.Debug("The link checker definitions were last updated " + ts2.TotalHours + " hours ago, downloading new list.");
Parsers.LinkCheckers.Engines.UniversalEngine.GetLinkCheckerDefinitions();
}
}
/// <summary>
/// Restarts if needed.
/// </summary>
public static void RestartIfNeeded()
{
var memlimit = Settings.Get("Memory Usage Limit", 512);
var oldusage = Process.GetCurrentProcess().WorkingSet64;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
GC.Collect();
var memusage = Process.GetCurrentProcess().WorkingSet64;
Log.Debug("Current memory usage is " + Utils.GetFileSize(memusage) + " (GC: " + (memusage < oldusage ? "-" : "+") + Utils.GetFileSize(Math.Abs(memusage - oldusage)) + "; Since last: " + (memusage < _lastMemUse ? "-" : "+") + Utils.GetFileSize(Math.Abs(memusage - _lastMemUse)) + "); " + (memlimit < 256 ? "auto-restart disabled." : "auto-restarting after " + memlimit + " MB."));
_lastMemUse = memusage;
if (memlimit < 256)
{
return;
}
if ((memlimit * 1048576L) < memusage)
{
MainWindow.Active.Restart();
}
}
}
}