TaskManager.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Model.Events;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using MediaBrowser.Model.Tasks;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Common.Implementations.ScheduledTasks
  13. {
  14. /// <summary>
  15. /// Class TaskManager
  16. /// </summary>
  17. public class TaskManager : ITaskManager
  18. {
  19. public event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting;
  20. public event EventHandler<TaskCompletionEventArgs> TaskCompleted;
  21. /// <summary>
  22. /// Gets the list of Scheduled Tasks
  23. /// </summary>
  24. /// <value>The scheduled tasks.</value>
  25. public IScheduledTaskWorker[] ScheduledTasks { get; private set; }
  26. /// <summary>
  27. /// The _task queue
  28. /// </summary>
  29. private readonly SortedDictionary<Type, TaskExecutionOptions> _taskQueue = new SortedDictionary<Type, TaskExecutionOptions>();
  30. /// <summary>
  31. /// Gets or sets the json serializer.
  32. /// </summary>
  33. /// <value>The json serializer.</value>
  34. private IJsonSerializer JsonSerializer { get; set; }
  35. /// <summary>
  36. /// Gets or sets the application paths.
  37. /// </summary>
  38. /// <value>The application paths.</value>
  39. private IApplicationPaths ApplicationPaths { get; set; }
  40. /// <summary>
  41. /// Gets the logger.
  42. /// </summary>
  43. /// <value>The logger.</value>
  44. private ILogger Logger { get; set; }
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="TaskManager" /> class.
  47. /// </summary>
  48. /// <param name="applicationPaths">The application paths.</param>
  49. /// <param name="jsonSerializer">The json serializer.</param>
  50. /// <param name="logger">The logger.</param>
  51. /// <exception cref="System.ArgumentException">kernel</exception>
  52. public TaskManager(IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILogger logger)
  53. {
  54. ApplicationPaths = applicationPaths;
  55. JsonSerializer = jsonSerializer;
  56. Logger = logger;
  57. ScheduledTasks = new IScheduledTaskWorker[] { };
  58. }
  59. /// <summary>
  60. /// Cancels if running and queue.
  61. /// </summary>
  62. /// <typeparam name="T"></typeparam>
  63. /// <param name="options">Task options.</param>
  64. public void CancelIfRunningAndQueue<T>(TaskExecutionOptions options)
  65. where T : IScheduledTask
  66. {
  67. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  68. ((ScheduledTaskWorker)task).CancelIfRunning();
  69. QueueScheduledTask<T>(options);
  70. }
  71. public void CancelIfRunningAndQueue<T>()
  72. where T : IScheduledTask
  73. {
  74. CancelIfRunningAndQueue<T>(new TaskExecutionOptions());
  75. }
  76. /// <summary>
  77. /// Cancels if running
  78. /// </summary>
  79. /// <typeparam name="T"></typeparam>
  80. public void CancelIfRunning<T>()
  81. where T : IScheduledTask
  82. {
  83. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  84. ((ScheduledTaskWorker)task).CancelIfRunning();
  85. }
  86. /// <summary>
  87. /// Queues the scheduled task.
  88. /// </summary>
  89. /// <typeparam name="T"></typeparam>
  90. /// <param name="options">Task options</param>
  91. public void QueueScheduledTask<T>(TaskExecutionOptions options)
  92. where T : IScheduledTask
  93. {
  94. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  95. QueueScheduledTask(scheduledTask, options);
  96. }
  97. public void QueueScheduledTask<T>()
  98. where T : IScheduledTask
  99. {
  100. QueueScheduledTask<T>(new TaskExecutionOptions());
  101. }
  102. /// <summary>
  103. /// Queues the scheduled task.
  104. /// </summary>
  105. /// <param name="task">The task.</param>
  106. /// <param name="options">The task options.</param>
  107. public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
  108. {
  109. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == task.GetType());
  110. QueueScheduledTask(scheduledTask, options);
  111. }
  112. /// <summary>
  113. /// Queues the scheduled task.
  114. /// </summary>
  115. /// <param name="task">The task.</param>
  116. /// <param name="options">The task options.</param>
  117. private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
  118. {
  119. var type = task.ScheduledTask.GetType();
  120. lock (_taskQueue)
  121. {
  122. // If it's idle just execute immediately
  123. if (task.State == TaskState.Idle)
  124. {
  125. Execute(task, options);
  126. return;
  127. }
  128. if (!_taskQueue.ContainsKey(type))
  129. {
  130. Logger.Info("Queueing task {0}", type.Name);
  131. _taskQueue.Add(type, options);
  132. }
  133. else
  134. {
  135. _taskQueue[type] = options;
  136. Logger.Info("Task already queued: {0}", type.Name);
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Adds the tasks.
  142. /// </summary>
  143. /// <param name="tasks">The tasks.</param>
  144. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  145. {
  146. var myTasks = ScheduledTasks.ToList();
  147. var list = tasks.ToList();
  148. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger)));
  149. ScheduledTasks = myTasks.ToArray();
  150. }
  151. /// <summary>
  152. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  153. /// </summary>
  154. public void Dispose()
  155. {
  156. Dispose(true);
  157. GC.SuppressFinalize(this);
  158. }
  159. /// <summary>
  160. /// Releases unmanaged and - optionally - managed resources.
  161. /// </summary>
  162. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  163. protected virtual void Dispose(bool dispose)
  164. {
  165. foreach (var task in ScheduledTasks)
  166. {
  167. task.Dispose();
  168. }
  169. }
  170. public void Cancel(IScheduledTaskWorker task)
  171. {
  172. ((ScheduledTaskWorker)task).Cancel();
  173. }
  174. public Task Execute(IScheduledTaskWorker task, TaskExecutionOptions options)
  175. {
  176. return ((ScheduledTaskWorker)task).Execute(options);
  177. }
  178. /// <summary>
  179. /// Called when [task executing].
  180. /// </summary>
  181. /// <param name="task">The task.</param>
  182. internal void OnTaskExecuting(IScheduledTaskWorker task)
  183. {
  184. EventHelper.FireEventIfNotNull(TaskExecuting, this, new GenericEventArgs<IScheduledTaskWorker>
  185. {
  186. Argument = task
  187. }, Logger);
  188. }
  189. /// <summary>
  190. /// Called when [task completed].
  191. /// </summary>
  192. /// <param name="task">The task.</param>
  193. /// <param name="result">The result.</param>
  194. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  195. {
  196. EventHelper.FireEventIfNotNull(TaskCompleted, task, new TaskCompletionEventArgs
  197. {
  198. Result = result,
  199. Task = task
  200. }, Logger);
  201. ExecuteQueuedTasks();
  202. }
  203. /// <summary>
  204. /// Executes the queued tasks.
  205. /// </summary>
  206. private void ExecuteQueuedTasks()
  207. {
  208. // Execute queued tasks
  209. lock (_taskQueue)
  210. {
  211. foreach (var enqueuedType in _taskQueue.ToList())
  212. {
  213. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Key);
  214. if (scheduledTask.State == TaskState.Idle)
  215. {
  216. Execute(scheduledTask, enqueuedType.Value);
  217. _taskQueue.Remove(enqueuedType.Key);
  218. }
  219. }
  220. }
  221. }
  222. }
  223. }