TaskManager.cs 9.6 KB

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