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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
|
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Serialization;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Tasks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Common.ScheduledTasks
{
/// <summary>
/// Represents a task that can be executed at a scheduled time
/// </summary>
/// <typeparam name="TKernelType">The type of the T kernel type.</typeparam>
public abstract class BaseScheduledTask<TKernelType> : IScheduledTask
where TKernelType : IKernel
{
/// <summary>
/// Gets the kernel.
/// </summary>
/// <value>The kernel.</value>
protected TKernelType Kernel { get; private set; }
/// <summary>
/// The _last execution result
/// </summary>
private TaskResult _lastExecutionResult;
/// <summary>
/// The _last execution resultinitialized
/// </summary>
private bool _lastExecutionResultinitialized;
/// <summary>
/// The _last execution result sync lock
/// </summary>
private object _lastExecutionResultSyncLock = new object();
/// <summary>
/// Gets the last execution result.
/// </summary>
/// <value>The last execution result.</value>
public TaskResult LastExecutionResult
{
get
{
LazyInitializer.EnsureInitialized(ref _lastExecutionResult, ref _lastExecutionResultinitialized, ref _lastExecutionResultSyncLock, () =>
{
try
{
return JsonSerializer.DeserializeFromFile<TaskResult>(HistoryFilePath);
}
catch (IOException)
{
// File doesn't exist. No biggie
return null;
}
});
return _lastExecutionResult;
}
private set
{
_lastExecutionResult = value;
_lastExecutionResultinitialized = value != null;
}
}
/// <summary>
/// The _scheduled tasks data directory
/// </summary>
private string _scheduledTasksDataDirectory;
/// <summary>
/// Gets the scheduled tasks data directory.
/// </summary>
/// <value>The scheduled tasks data directory.</value>
private string ScheduledTasksDataDirectory
{
get
{
if (_scheduledTasksDataDirectory == null)
{
_scheduledTasksDataDirectory = Path.Combine(Kernel.ApplicationPaths.DataPath, "ScheduledTasks");
if (!Directory.Exists(_scheduledTasksDataDirectory))
{
Directory.CreateDirectory(_scheduledTasksDataDirectory);
}
}
return _scheduledTasksDataDirectory;
}
}
/// <summary>
/// The _scheduled tasks configuration directory
/// </summary>
private string _scheduledTasksConfigurationDirectory;
/// <summary>
/// Gets the scheduled tasks configuration directory.
/// </summary>
/// <value>The scheduled tasks configuration directory.</value>
private string ScheduledTasksConfigurationDirectory
{
get
{
if (_scheduledTasksConfigurationDirectory == null)
{
_scheduledTasksConfigurationDirectory = Path.Combine(Kernel.ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
if (!Directory.Exists(_scheduledTasksConfigurationDirectory))
{
Directory.CreateDirectory(_scheduledTasksConfigurationDirectory);
}
}
return _scheduledTasksConfigurationDirectory;
}
}
/// <summary>
/// Gets the configuration file path.
/// </summary>
/// <value>The configuration file path.</value>
private string ConfigurationFilePath
{
get { return Path.Combine(ScheduledTasksConfigurationDirectory, Id + ".js"); }
}
/// <summary>
/// Gets the history file path.
/// </summary>
/// <value>The history file path.</value>
private string HistoryFilePath
{
get { return Path.Combine(ScheduledTasksDataDirectory, Id + ".js"); }
}
/// <summary>
/// Gets the current cancellation token
/// </summary>
/// <value>The current cancellation token source.</value>
private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
/// <summary>
/// Gets or sets the current execution start time.
/// </summary>
/// <value>The current execution start time.</value>
private DateTime CurrentExecutionStartTime { get; set; }
/// <summary>
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public TaskState State
{
get
{
if (CurrentCancellationTokenSource != null)
{
return CurrentCancellationTokenSource.IsCancellationRequested
? TaskState.Cancelling
: TaskState.Running;
}
return TaskState.Idle;
}
}
/// <summary>
/// Gets the current progress.
/// </summary>
/// <value>The current progress.</value>
public double? CurrentProgress { get; private set; }
/// <summary>
/// The _triggers
/// </summary>
private IEnumerable<BaseTaskTrigger> _triggers;
/// <summary>
/// The _triggers initialized
/// </summary>
private bool _triggersInitialized;
/// <summary>
/// The _triggers sync lock
/// </summary>
private object _triggersSyncLock = new object();
/// <summary>
/// Gets the triggers that define when the task will run
/// </summary>
/// <value>The triggers.</value>
/// <exception cref="System.ArgumentNullException">value</exception>
public IEnumerable<BaseTaskTrigger> Triggers
{
get
{
LazyInitializer.EnsureInitialized(ref _triggers, ref _triggersInitialized, ref _triggersSyncLock, () =>
{
try
{
return JsonSerializer.DeserializeFromFile<IEnumerable<TaskTriggerInfo>>(ConfigurationFilePath)
.Select(t => ScheduledTaskHelpers.GetTrigger(t, Kernel))
.ToList();
}
catch (IOException)
{
// File doesn't exist. No biggie. Return defaults.
return GetDefaultTriggers();
}
});
return _triggers;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// Cleanup current triggers
if (_triggers != null)
{
DisposeTriggers();
}
_triggers = value.ToList();
_triggersInitialized = true;
ReloadTriggerEvents();
JsonSerializer.SerializeToFile(_triggers.Select(ScheduledTaskHelpers.GetTriggerInfo), ConfigurationFilePath);
}
}
/// <summary>
/// Creates the triggers that define when the task will run
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
protected abstract IEnumerable<BaseTaskTrigger> GetDefaultTriggers();
/// <summary>
/// Returns the task to be executed
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
/// <returns>Task.</returns>
protected abstract Task ExecuteInternal(CancellationToken cancellationToken, IProgress<double> progress);
/// <summary>
/// Gets the name of the task
/// </summary>
/// <value>The name.</value>
public abstract string Name { get; }
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public abstract string Description { get; }
/// <summary>
/// Gets the category.
/// </summary>
/// <value>The category.</value>
public virtual string Category
{
get { return "Application"; }
}
/// <summary>
/// The _id
/// </summary>
private Guid? _id;
/// <summary>
/// Gets the unique id.
/// </summary>
/// <value>The unique id.</value>
public Guid Id
{
get
{
if (!_id.HasValue)
{
_id = GetType().FullName.GetMD5();
}
return _id.Value;
}
}
/// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
protected ILogger Logger { get; private set; }
/// <summary>
/// Initializes the specified kernel.
/// </summary>
/// <param name="kernel">The kernel.</param>
/// <param name="logger">The logger.</param>
public void Initialize(IKernel kernel, ILogger logger)
{
Logger = logger;
Kernel = (TKernelType)kernel;
ReloadTriggerEvents();
}
/// <summary>
/// Reloads the trigger events.
/// </summary>
private void ReloadTriggerEvents()
{
foreach (var trigger in Triggers)
{
trigger.Stop();
trigger.Triggered -= trigger_Triggered;
trigger.Triggered += trigger_Triggered;
trigger.Start();
}
}
/// <summary>
/// Handles the Triggered event of the trigger control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void trigger_Triggered(object sender, EventArgs e)
{
var trigger = (BaseTaskTrigger)sender;
Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name);
Kernel.TaskManager.QueueScheduledTask(this);
}
/// <summary>
/// Executes the task
/// </summary>
/// <returns>Task.</returns>
/// <exception cref="System.InvalidOperationException">Cannot execute a Task that is already running</exception>
public async Task Execute()
{
// Cancel the current execution, if any
if (CurrentCancellationTokenSource != null)
{
throw new InvalidOperationException("Cannot execute a Task that is already running");
}
CurrentCancellationTokenSource = new CancellationTokenSource();
Logger.Info("Executing {0}", Name);
var progress = new Progress<double>();
progress.ProgressChanged += progress_ProgressChanged;
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
Kernel.TcpManager.SendWebSocketMessage("ScheduledTaskBeginExecute", Name);
try
{
await Task.Run(async () => await ExecuteInternal(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false)).ConfigureAwait(false);
status = TaskCompletionStatus.Completed;
}
catch (OperationCanceledException)
{
status = TaskCompletionStatus.Cancelled;
}
catch (Exception ex)
{
Logger.ErrorException("Error", ex);
status = TaskCompletionStatus.Failed;
}
var endTime = DateTime.UtcNow;
LogResult(endTime, status);
Kernel.TcpManager.SendWebSocketMessage("ScheduledTaskEndExecute", LastExecutionResult);
progress.ProgressChanged -= progress_ProgressChanged;
CurrentCancellationTokenSource.Dispose();
CurrentCancellationTokenSource = null;
CurrentProgress = null;
Kernel.TaskManager.OnTaskCompleted(this);
}
/// <summary>
/// Logs the result.
/// </summary>
/// <param name="endTime">The end time.</param>
/// <param name="status">The status.</param>
private void LogResult(DateTime endTime, TaskCompletionStatus status)
{
var startTime = CurrentExecutionStartTime;
var elapsedTime = endTime - startTime;
Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
var result = new TaskResult
{
StartTimeUtc = startTime,
EndTimeUtc = endTime,
Status = status,
Name = Name,
Id = Id
};
JsonSerializer.SerializeToFile(result, HistoryFilePath);
LastExecutionResult = result;
}
/// <summary>
/// Progress_s the progress changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void progress_ProgressChanged(object sender, double e)
{
CurrentProgress = e;
}
/// <summary>
/// Stops the task if it is currently executing
/// </summary>
/// <exception cref="System.InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
public void Cancel()
{
if (State != TaskState.Running)
{
throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
}
CancelIfRunning();
}
/// <summary>
/// Cancels if running.
/// </summary>
public void CancelIfRunning()
{
if (State == TaskState.Running)
{
Logger.Info("Attempting to cancel Scheduled Task {0}", Name);
CurrentCancellationTokenSource.Cancel();
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
DisposeTriggers();
if (State == TaskState.Running)
{
LogResult(DateTime.UtcNow, TaskCompletionStatus.Aborted);
}
if (CurrentCancellationTokenSource != null)
{
CurrentCancellationTokenSource.Dispose();
}
}
}
/// <summary>
/// Disposes each trigger
/// </summary>
private void DisposeTriggers()
{
foreach (var trigger in Triggers)
{
trigger.Triggered -= trigger_Triggered;
trigger.Dispose();
}
}
}
}
|