TaskManager.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. /// <summary>
  72. /// Cancels if running
  73. /// </summary>
  74. /// <typeparam name="T"></typeparam>
  75. public void CancelIfRunning<T>()
  76. where T : IScheduledTask
  77. {
  78. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  79. ((ScheduledTaskWorker)task).CancelIfRunning();
  80. }
  81. /// <summary>
  82. /// Queues the scheduled task.
  83. /// </summary>
  84. /// <typeparam name="T"></typeparam>
  85. /// <param name="options">Task options</param>
  86. public void QueueScheduledTask<T>(TaskExecutionOptions options)
  87. where T : IScheduledTask
  88. {
  89. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  90. QueueScheduledTask(scheduledTask, options);
  91. }
  92. /// <summary>
  93. /// Queues the scheduled task.
  94. /// </summary>
  95. /// <param name="task">The task.</param>
  96. /// <param name="options">The task options.</param>
  97. public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
  98. {
  99. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == task.GetType());
  100. QueueScheduledTask(scheduledTask, options);
  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. private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
  108. {
  109. var type = task.ScheduledTask.GetType();
  110. lock (_taskQueue)
  111. {
  112. // If it's idle just execute immediately
  113. if (task.State == TaskState.Idle)
  114. {
  115. Execute(task, options);
  116. return;
  117. }
  118. if (!_taskQueue.ContainsKey(type))
  119. {
  120. Logger.Info("Queueing task {0}", type.Name);
  121. _taskQueue.Add(type, options);
  122. }
  123. else
  124. {
  125. _taskQueue[type] = options;
  126. Logger.Info("Task already queued: {0}", type.Name);
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// Adds the tasks.
  132. /// </summary>
  133. /// <param name="tasks">The tasks.</param>
  134. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  135. {
  136. var myTasks = ScheduledTasks.ToList();
  137. var list = tasks.ToList();
  138. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger)));
  139. ScheduledTasks = myTasks.ToArray();
  140. }
  141. /// <summary>
  142. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  143. /// </summary>
  144. public void Dispose()
  145. {
  146. Dispose(true);
  147. GC.SuppressFinalize(this);
  148. }
  149. /// <summary>
  150. /// Releases unmanaged and - optionally - managed resources.
  151. /// </summary>
  152. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  153. protected virtual void Dispose(bool dispose)
  154. {
  155. foreach (var task in ScheduledTasks)
  156. {
  157. task.Dispose();
  158. }
  159. }
  160. public void Cancel(IScheduledTaskWorker task)
  161. {
  162. ((ScheduledTaskWorker)task).Cancel();
  163. }
  164. public Task Execute(IScheduledTaskWorker task, TaskExecutionOptions options)
  165. {
  166. return ((ScheduledTaskWorker)task).Execute(options);
  167. }
  168. /// <summary>
  169. /// Called when [task executing].
  170. /// </summary>
  171. /// <param name="task">The task.</param>
  172. internal void OnTaskExecuting(IScheduledTaskWorker task)
  173. {
  174. EventHelper.FireEventIfNotNull(TaskExecuting, this, new GenericEventArgs<IScheduledTaskWorker>
  175. {
  176. Argument = task
  177. }, Logger);
  178. }
  179. /// <summary>
  180. /// Called when [task completed].
  181. /// </summary>
  182. /// <param name="task">The task.</param>
  183. /// <param name="result">The result.</param>
  184. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  185. {
  186. EventHelper.FireEventIfNotNull(TaskCompleted, task, new TaskCompletionEventArgs
  187. {
  188. Result = result,
  189. Task = task
  190. }, Logger);
  191. ExecuteQueuedTasks();
  192. }
  193. /// <summary>
  194. /// Executes the queued tasks.
  195. /// </summary>
  196. private void ExecuteQueuedTasks()
  197. {
  198. // Execute queued tasks
  199. lock (_taskQueue)
  200. {
  201. foreach (var enqueuedType in _taskQueue.ToList())
  202. {
  203. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Key);
  204. if (scheduledTask.State == TaskState.Idle)
  205. {
  206. Execute(scheduledTask, enqueuedType.Value);
  207. _taskQueue.Remove(enqueuedType.Key);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }