TaskManager.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.Events;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Serialization;
  11. using MediaBrowser.Model.Tasks;
  12. using Microsoft.Extensions.Logging;
  13. namespace Emby.Server.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, TaskOptions>> _taskQueue =
  31. new ConcurrentQueue<Tuple<Type, TaskOptions>>();
  32. private readonly IJsonSerializer _jsonSerializer;
  33. private readonly IApplicationPaths _applicationPaths;
  34. private readonly ILogger<TaskManager> _logger;
  35. private readonly IFileSystem _fileSystem;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="TaskManager" /> class.
  38. /// </summary>
  39. /// <param name="applicationPaths">The application paths.</param>
  40. /// <param name="jsonSerializer">The json serializer.</param>
  41. /// <param name="logger">The logger.</param>
  42. /// <param name="fileSystem">The filesystem manager.</param>
  43. public TaskManager(
  44. IApplicationPaths applicationPaths,
  45. IJsonSerializer jsonSerializer,
  46. ILogger<TaskManager> logger,
  47. IFileSystem fileSystem)
  48. {
  49. _applicationPaths = applicationPaths;
  50. _jsonSerializer = jsonSerializer;
  51. _logger = logger;
  52. _fileSystem = fileSystem;
  53. ScheduledTasks = Array.Empty<IScheduledTaskWorker>();
  54. }
  55. /// <summary>
  56. /// Cancels if running and queue.
  57. /// </summary>
  58. /// <typeparam name="T"></typeparam>
  59. /// <param name="options">Task options.</param>
  60. public void CancelIfRunningAndQueue<T>(TaskOptions options)
  61. where T : IScheduledTask
  62. {
  63. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  64. ((ScheduledTaskWorker)task).CancelIfRunning();
  65. QueueScheduledTask<T>(options);
  66. }
  67. public void CancelIfRunningAndQueue<T>()
  68. where T : IScheduledTask
  69. {
  70. CancelIfRunningAndQueue<T>(new TaskOptions());
  71. }
  72. /// <summary>
  73. /// Cancels if running.
  74. /// </summary>
  75. /// <typeparam name="T"></typeparam>
  76. public void CancelIfRunning<T>()
  77. where T : IScheduledTask
  78. {
  79. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  80. ((ScheduledTaskWorker)task).CancelIfRunning();
  81. }
  82. /// <summary>
  83. /// Queues the scheduled task.
  84. /// </summary>
  85. /// <typeparam name="T"></typeparam>
  86. /// <param name="options">Task options</param>
  87. public void QueueScheduledTask<T>(TaskOptions options)
  88. where T : IScheduledTask
  89. {
  90. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  91. if (scheduledTask == null)
  92. {
  93. _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
  94. }
  95. else
  96. {
  97. QueueScheduledTask(scheduledTask, options);
  98. }
  99. }
  100. public void QueueScheduledTask<T>()
  101. where T : IScheduledTask
  102. {
  103. QueueScheduledTask<T>(new TaskOptions());
  104. }
  105. public void QueueIfNotRunning<T>()
  106. where T : IScheduledTask
  107. {
  108. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  109. if (task.State != TaskState.Running)
  110. {
  111. QueueScheduledTask<T>(new TaskOptions());
  112. }
  113. }
  114. public void Execute<T>()
  115. where T : IScheduledTask
  116. {
  117. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  118. if (scheduledTask == null)
  119. {
  120. _logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
  121. }
  122. else
  123. {
  124. var type = scheduledTask.ScheduledTask.GetType();
  125. _logger.LogInformation("Queueing task {0}", type.Name);
  126. lock (_taskQueue)
  127. {
  128. if (scheduledTask.State == TaskState.Idle)
  129. {
  130. Execute(scheduledTask, new TaskOptions());
  131. }
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Queues the scheduled task.
  137. /// </summary>
  138. /// <param name="task">The task.</param>
  139. /// <param name="options">The task options.</param>
  140. public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
  141. {
  142. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  143. if (scheduledTask == null)
  144. {
  145. _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
  146. }
  147. else
  148. {
  149. QueueScheduledTask(scheduledTask, options);
  150. }
  151. }
  152. /// <summary>
  153. /// Queues the scheduled task.
  154. /// </summary>
  155. /// <param name="task">The task.</param>
  156. /// <param name="options">The task options.</param>
  157. private void QueueScheduledTask(IScheduledTaskWorker task, TaskOptions options)
  158. {
  159. var type = task.ScheduledTask.GetType();
  160. _logger.LogInformation("Queueing task {0}", type.Name);
  161. lock (_taskQueue)
  162. {
  163. if (task.State == TaskState.Idle)
  164. {
  165. Execute(task, options);
  166. return;
  167. }
  168. _taskQueue.Enqueue(new Tuple<Type, TaskOptions>(type, options));
  169. }
  170. }
  171. /// <summary>
  172. /// Adds the tasks.
  173. /// </summary>
  174. /// <param name="tasks">The tasks.</param>
  175. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  176. {
  177. var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _jsonSerializer, _logger));
  178. ScheduledTasks = ScheduledTasks.Concat(list).ToArray();
  179. }
  180. /// <summary>
  181. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  182. /// </summary>
  183. public void Dispose()
  184. {
  185. Dispose(true);
  186. }
  187. /// <summary>
  188. /// Releases unmanaged and - optionally - managed resources.
  189. /// </summary>
  190. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  191. protected virtual void Dispose(bool dispose)
  192. {
  193. foreach (var task in ScheduledTasks)
  194. {
  195. task.Dispose();
  196. }
  197. }
  198. public void Cancel(IScheduledTaskWorker task)
  199. {
  200. ((ScheduledTaskWorker)task).Cancel();
  201. }
  202. public Task Execute(IScheduledTaskWorker task, TaskOptions options)
  203. {
  204. return ((ScheduledTaskWorker)task).Execute(options);
  205. }
  206. /// <summary>
  207. /// Called when [task executing].
  208. /// </summary>
  209. /// <param name="task">The task.</param>
  210. internal void OnTaskExecuting(IScheduledTaskWorker task)
  211. {
  212. TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>(task));
  213. }
  214. /// <summary>
  215. /// Called when [task completed].
  216. /// </summary>
  217. /// <param name="task">The task.</param>
  218. /// <param name="result">The result.</param>
  219. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  220. {
  221. TaskCompleted?.Invoke(task, new TaskCompletionEventArgs(task, result));
  222. ExecuteQueuedTasks();
  223. }
  224. /// <summary>
  225. /// Executes the queued tasks.
  226. /// </summary>
  227. private void ExecuteQueuedTasks()
  228. {
  229. _logger.LogInformation("ExecuteQueuedTasks");
  230. // Execute queued tasks
  231. lock (_taskQueue)
  232. {
  233. var list = new List<Tuple<Type, TaskOptions>>();
  234. while (_taskQueue.TryDequeue(out var item))
  235. {
  236. if (list.All(i => i.Item1 != item.Item1))
  237. {
  238. list.Add(item);
  239. }
  240. }
  241. foreach (var enqueuedType in list)
  242. {
  243. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
  244. if (scheduledTask.State == TaskState.Idle)
  245. {
  246. Execute(scheduledTask, enqueuedType.Item2);
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }