TaskManager.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  97. if (scheduledTask == null)
  98. {
  99. Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
  100. }
  101. else
  102. {
  103. QueueScheduledTask(scheduledTask, options);
  104. }
  105. }
  106. public void QueueScheduledTask<T>()
  107. where T : IScheduledTask
  108. {
  109. QueueScheduledTask<T>(new TaskExecutionOptions());
  110. }
  111. /// <summary>
  112. /// Queues the scheduled task.
  113. /// </summary>
  114. /// <param name="task">The task.</param>
  115. /// <param name="options">The task options.</param>
  116. public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
  117. {
  118. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  119. if (scheduledTask == null)
  120. {
  121. Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
  122. }
  123. else
  124. {
  125. QueueScheduledTask(scheduledTask, options);
  126. }
  127. }
  128. /// <summary>
  129. /// Queues the scheduled task.
  130. /// </summary>
  131. /// <param name="task">The task.</param>
  132. /// <param name="options">The task options.</param>
  133. private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
  134. {
  135. var type = task.ScheduledTask.GetType();
  136. Logger.Info("Queueing task {0}", type.Name);
  137. lock (_taskQueue)
  138. {
  139. if (task.State == TaskState.Idle)
  140. {
  141. Execute(task, options);
  142. return;
  143. }
  144. _taskQueue.Enqueue(new Tuple<Type, TaskExecutionOptions>(type, options));
  145. }
  146. }
  147. /// <summary>
  148. /// Adds the tasks.
  149. /// </summary>
  150. /// <param name="tasks">The tasks.</param>
  151. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  152. {
  153. var myTasks = ScheduledTasks.ToList();
  154. var list = tasks.ToList();
  155. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger)));
  156. ScheduledTasks = myTasks.ToArray();
  157. }
  158. /// <summary>
  159. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  160. /// </summary>
  161. public void Dispose()
  162. {
  163. Dispose(true);
  164. GC.SuppressFinalize(this);
  165. }
  166. /// <summary>
  167. /// Releases unmanaged and - optionally - managed resources.
  168. /// </summary>
  169. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  170. protected virtual void Dispose(bool dispose)
  171. {
  172. foreach (var task in ScheduledTasks)
  173. {
  174. task.Dispose();
  175. }
  176. }
  177. public void Cancel(IScheduledTaskWorker task)
  178. {
  179. ((ScheduledTaskWorker)task).Cancel();
  180. }
  181. public Task Execute(IScheduledTaskWorker task, TaskExecutionOptions options)
  182. {
  183. return ((ScheduledTaskWorker)task).Execute(options);
  184. }
  185. /// <summary>
  186. /// Called when [task executing].
  187. /// </summary>
  188. /// <param name="task">The task.</param>
  189. internal void OnTaskExecuting(IScheduledTaskWorker task)
  190. {
  191. EventHelper.FireEventIfNotNull(TaskExecuting, this, new GenericEventArgs<IScheduledTaskWorker>
  192. {
  193. Argument = task
  194. }, Logger);
  195. }
  196. /// <summary>
  197. /// Called when [task completed].
  198. /// </summary>
  199. /// <param name="task">The task.</param>
  200. /// <param name="result">The result.</param>
  201. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  202. {
  203. EventHelper.FireEventIfNotNull(TaskCompleted, task, new TaskCompletionEventArgs
  204. {
  205. Result = result,
  206. Task = task
  207. }, Logger);
  208. ExecuteQueuedTasks();
  209. }
  210. /// <summary>
  211. /// Executes the queued tasks.
  212. /// </summary>
  213. private void ExecuteQueuedTasks()
  214. {
  215. // Execute queued tasks
  216. lock (_taskQueue)
  217. {
  218. var list = new List<Tuple<Type, TaskExecutionOptions>>();
  219. Tuple<Type, TaskExecutionOptions> item;
  220. while (_taskQueue.TryDequeue(out item))
  221. {
  222. if (list.All(i => i.Item1 != item.Item1))
  223. {
  224. list.Add(item);
  225. }
  226. }
  227. foreach (var enqueuedType in list)
  228. {
  229. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
  230. if (scheduledTask.State == TaskState.Idle)
  231. {
  232. Execute(scheduledTask, enqueuedType.Item2);
  233. }
  234. }
  235. }
  236. }
  237. }
  238. }