BaseScheduledTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Kernel;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Model.Tasks;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Common.ScheduledTasks
  12. {
  13. /// <summary>
  14. /// Represents a task that can be executed at a scheduled time
  15. /// </summary>
  16. /// <typeparam name="TKernelType">The type of the T kernel type.</typeparam>
  17. public abstract class BaseScheduledTask<TKernelType> : IScheduledTask
  18. where TKernelType : class, IKernel
  19. {
  20. /// <summary>
  21. /// Gets the kernel.
  22. /// </summary>
  23. /// <value>The kernel.</value>
  24. protected TKernelType Kernel { get; private set; }
  25. /// <summary>
  26. /// Gets the logger.
  27. /// </summary>
  28. /// <value>The logger.</value>
  29. protected ILogger Logger { get; private set; }
  30. /// <summary>
  31. /// Gets the task manager.
  32. /// </summary>
  33. /// <value>The task manager.</value>
  34. protected ITaskManager TaskManager { get; private set; }
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="BaseScheduledTask{TKernelType}" /> class.
  37. /// </summary>
  38. /// <param name="kernel">The kernel.</param>
  39. /// <param name="taskManager">The task manager.</param>
  40. /// <param name="logger">The logger.</param>
  41. /// <exception cref="System.ArgumentNullException">kernel</exception>
  42. protected BaseScheduledTask(TKernelType kernel, ITaskManager taskManager, ILogger logger)
  43. {
  44. if (kernel == null)
  45. {
  46. throw new ArgumentNullException("kernel");
  47. }
  48. if (taskManager == null)
  49. {
  50. throw new ArgumentNullException("taskManager");
  51. }
  52. if (logger == null)
  53. {
  54. throw new ArgumentNullException("logger");
  55. }
  56. Kernel = kernel;
  57. TaskManager = taskManager;
  58. Logger = logger;
  59. ReloadTriggerEvents(true);
  60. }
  61. /// <summary>
  62. /// The _last execution result
  63. /// </summary>
  64. private TaskResult _lastExecutionResult;
  65. /// <summary>
  66. /// The _last execution resultinitialized
  67. /// </summary>
  68. private bool _lastExecutionResultinitialized;
  69. /// <summary>
  70. /// The _last execution result sync lock
  71. /// </summary>
  72. private object _lastExecutionResultSyncLock = new object();
  73. /// <summary>
  74. /// Gets the last execution result.
  75. /// </summary>
  76. /// <value>The last execution result.</value>
  77. public TaskResult LastExecutionResult
  78. {
  79. get
  80. {
  81. LazyInitializer.EnsureInitialized(ref _lastExecutionResult, ref _lastExecutionResultinitialized, ref _lastExecutionResultSyncLock, () =>
  82. {
  83. try
  84. {
  85. return TaskManager.GetLastExecutionResult(this);
  86. }
  87. catch (IOException)
  88. {
  89. // File doesn't exist. No biggie
  90. return null;
  91. }
  92. });
  93. return _lastExecutionResult;
  94. }
  95. private set
  96. {
  97. _lastExecutionResult = value;
  98. _lastExecutionResultinitialized = value != null;
  99. }
  100. }
  101. /// <summary>
  102. /// Gets the current cancellation token
  103. /// </summary>
  104. /// <value>The current cancellation token source.</value>
  105. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  106. /// <summary>
  107. /// Gets or sets the current execution start time.
  108. /// </summary>
  109. /// <value>The current execution start time.</value>
  110. private DateTime CurrentExecutionStartTime { get; set; }
  111. /// <summary>
  112. /// Gets the state.
  113. /// </summary>
  114. /// <value>The state.</value>
  115. public TaskState State
  116. {
  117. get
  118. {
  119. if (CurrentCancellationTokenSource != null)
  120. {
  121. return CurrentCancellationTokenSource.IsCancellationRequested
  122. ? TaskState.Cancelling
  123. : TaskState.Running;
  124. }
  125. return TaskState.Idle;
  126. }
  127. }
  128. /// <summary>
  129. /// Gets the current progress.
  130. /// </summary>
  131. /// <value>The current progress.</value>
  132. public double? CurrentProgress { get; private set; }
  133. /// <summary>
  134. /// The _triggers
  135. /// </summary>
  136. private IEnumerable<ITaskTrigger> _triggers;
  137. /// <summary>
  138. /// The _triggers initialized
  139. /// </summary>
  140. private bool _triggersInitialized;
  141. /// <summary>
  142. /// The _triggers sync lock
  143. /// </summary>
  144. private object _triggersSyncLock = new object();
  145. /// <summary>
  146. /// Gets the triggers that define when the task will run
  147. /// </summary>
  148. /// <value>The triggers.</value>
  149. /// <exception cref="System.ArgumentNullException">value</exception>
  150. public IEnumerable<ITaskTrigger> Triggers
  151. {
  152. get
  153. {
  154. LazyInitializer.EnsureInitialized(ref _triggers, ref _triggersInitialized, ref _triggersSyncLock, () => TaskManager.LoadTriggers(this));
  155. return _triggers;
  156. }
  157. set
  158. {
  159. if (value == null)
  160. {
  161. throw new ArgumentNullException("value");
  162. }
  163. // Cleanup current triggers
  164. if (_triggers != null)
  165. {
  166. DisposeTriggers();
  167. }
  168. _triggers = value.ToList();
  169. _triggersInitialized = true;
  170. ReloadTriggerEvents(false);
  171. TaskManager.SaveTriggers(this, _triggers);
  172. }
  173. }
  174. /// <summary>
  175. /// Creates the triggers that define when the task will run
  176. /// </summary>
  177. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  178. public abstract IEnumerable<ITaskTrigger> GetDefaultTriggers();
  179. /// <summary>
  180. /// Returns the task to be executed
  181. /// </summary>
  182. /// <param name="cancellationToken">The cancellation token.</param>
  183. /// <param name="progress">The progress.</param>
  184. /// <returns>Task.</returns>
  185. protected abstract Task ExecuteInternal(CancellationToken cancellationToken, IProgress<double> progress);
  186. /// <summary>
  187. /// Gets the name of the task
  188. /// </summary>
  189. /// <value>The name.</value>
  190. public abstract string Name { get; }
  191. /// <summary>
  192. /// Gets the description.
  193. /// </summary>
  194. /// <value>The description.</value>
  195. public abstract string Description { get; }
  196. /// <summary>
  197. /// Gets the category.
  198. /// </summary>
  199. /// <value>The category.</value>
  200. public virtual string Category
  201. {
  202. get { return "Application"; }
  203. }
  204. /// <summary>
  205. /// The _id
  206. /// </summary>
  207. private Guid? _id;
  208. /// <summary>
  209. /// Gets the unique id.
  210. /// </summary>
  211. /// <value>The unique id.</value>
  212. public Guid Id
  213. {
  214. get
  215. {
  216. if (!_id.HasValue)
  217. {
  218. _id = GetType().FullName.GetMD5();
  219. }
  220. return _id.Value;
  221. }
  222. }
  223. /// <summary>
  224. /// Reloads the trigger events.
  225. /// </summary>
  226. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  227. private void ReloadTriggerEvents(bool isApplicationStartup)
  228. {
  229. foreach (var trigger in Triggers)
  230. {
  231. trigger.Stop();
  232. trigger.Triggered -= trigger_Triggered;
  233. trigger.Triggered += trigger_Triggered;
  234. trigger.Start(isApplicationStartup);
  235. }
  236. }
  237. /// <summary>
  238. /// Handles the Triggered event of the trigger control.
  239. /// </summary>
  240. /// <param name="sender">The source of the event.</param>
  241. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  242. async void trigger_Triggered(object sender, EventArgs e)
  243. {
  244. var trigger = (ITaskTrigger)sender;
  245. Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name);
  246. trigger.Stop();
  247. TaskManager.QueueScheduledTask(this);
  248. await Task.Delay(1000).ConfigureAwait(false);
  249. trigger.Start(false);
  250. }
  251. /// <summary>
  252. /// Executes the task
  253. /// </summary>
  254. /// <returns>Task.</returns>
  255. /// <exception cref="System.InvalidOperationException">Cannot execute a Task that is already running</exception>
  256. public async Task Execute()
  257. {
  258. // Cancel the current execution, if any
  259. if (CurrentCancellationTokenSource != null)
  260. {
  261. throw new InvalidOperationException("Cannot execute a Task that is already running");
  262. }
  263. CurrentCancellationTokenSource = new CancellationTokenSource();
  264. Logger.Info("Executing {0}", Name);
  265. var progress = new Progress<double>();
  266. progress.ProgressChanged += progress_ProgressChanged;
  267. TaskCompletionStatus status;
  268. CurrentExecutionStartTime = DateTime.UtcNow;
  269. Kernel.TcpManager.SendWebSocketMessage("ScheduledTaskBeginExecute", Name);
  270. try
  271. {
  272. await Task.Run(async () => await ExecuteInternal(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false)).ConfigureAwait(false);
  273. status = TaskCompletionStatus.Completed;
  274. }
  275. catch (OperationCanceledException)
  276. {
  277. status = TaskCompletionStatus.Cancelled;
  278. }
  279. catch (Exception ex)
  280. {
  281. Logger.ErrorException("Error", ex);
  282. status = TaskCompletionStatus.Failed;
  283. }
  284. var startTime = CurrentExecutionStartTime;
  285. var endTime = DateTime.UtcNow;
  286. Kernel.TcpManager.SendWebSocketMessage("ScheduledTaskEndExecute", LastExecutionResult);
  287. progress.ProgressChanged -= progress_ProgressChanged;
  288. CurrentCancellationTokenSource.Dispose();
  289. CurrentCancellationTokenSource = null;
  290. CurrentProgress = null;
  291. TaskManager.OnTaskCompleted(this, startTime, endTime, status);
  292. }
  293. /// <summary>
  294. /// Progress_s the progress changed.
  295. /// </summary>
  296. /// <param name="sender">The sender.</param>
  297. /// <param name="e">The e.</param>
  298. void progress_ProgressChanged(object sender, double e)
  299. {
  300. CurrentProgress = e;
  301. }
  302. /// <summary>
  303. /// Stops the task if it is currently executing
  304. /// </summary>
  305. /// <exception cref="System.InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  306. public void Cancel()
  307. {
  308. if (State != TaskState.Running)
  309. {
  310. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  311. }
  312. CancelIfRunning();
  313. }
  314. /// <summary>
  315. /// Cancels if running.
  316. /// </summary>
  317. public void CancelIfRunning()
  318. {
  319. if (State == TaskState.Running)
  320. {
  321. Logger.Info("Attempting to cancel Scheduled Task {0}", Name);
  322. CurrentCancellationTokenSource.Cancel();
  323. }
  324. }
  325. /// <summary>
  326. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  327. /// </summary>
  328. public void Dispose()
  329. {
  330. Dispose(true);
  331. GC.SuppressFinalize(this);
  332. }
  333. /// <summary>
  334. /// Releases unmanaged and - optionally - managed resources.
  335. /// </summary>
  336. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  337. protected virtual void Dispose(bool dispose)
  338. {
  339. if (dispose)
  340. {
  341. DisposeTriggers();
  342. if (State == TaskState.Running)
  343. {
  344. TaskManager.OnTaskCompleted(this, CurrentExecutionStartTime, DateTime.UtcNow, TaskCompletionStatus.Aborted);
  345. }
  346. if (CurrentCancellationTokenSource != null)
  347. {
  348. CurrentCancellationTokenSource.Dispose();
  349. }
  350. }
  351. }
  352. /// <summary>
  353. /// Disposes each trigger
  354. /// </summary>
  355. private void DisposeTriggers()
  356. {
  357. foreach (var trigger in Triggers)
  358. {
  359. trigger.Triggered -= trigger_Triggered;
  360. trigger.Stop();
  361. }
  362. }
  363. }
  364. }