TaskManager.cs 9.2 KB

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