TaskManager.cs 8.6 KB

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