TaskManager.cs 9.2 KB

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