TaskManager.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Data.Events;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.Tasks;
  9. using Microsoft.Extensions.Logging;
  10. namespace Emby.Server.Implementations.ScheduledTasks;
  11. /// <summary>
  12. /// Class TaskManager.
  13. /// </summary>
  14. public class TaskManager : ITaskManager
  15. {
  16. /// <summary>
  17. /// The _task queue.
  18. /// </summary>
  19. private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue =
  20. new ConcurrentQueue<Tuple<Type, TaskOptions>>();
  21. private readonly IApplicationPaths _applicationPaths;
  22. private readonly ILogger<TaskManager> _logger;
  23. /// <summary>
  24. /// Initializes a new instance of the <see cref="TaskManager" /> class.
  25. /// </summary>
  26. /// <param name="applicationPaths">The application paths.</param>
  27. /// <param name="logger">The logger.</param>
  28. public TaskManager(
  29. IApplicationPaths applicationPaths,
  30. ILogger<TaskManager> logger)
  31. {
  32. _applicationPaths = applicationPaths;
  33. _logger = logger;
  34. ScheduledTasks = [];
  35. }
  36. /// <inheritdoc />
  37. public event EventHandler<GenericEventArgs<IScheduledTaskWorker>>? TaskExecuting;
  38. /// <inheritdoc />
  39. public event EventHandler<TaskCompletionEventArgs>? TaskCompleted;
  40. /// <inheritdoc />
  41. public IReadOnlyList<IScheduledTaskWorker> ScheduledTasks { get; private set; }
  42. /// <inheritdoc />
  43. public void CancelIfRunningAndQueue<T>(TaskOptions options)
  44. where T : IScheduledTask
  45. {
  46. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  47. ((ScheduledTaskWorker)task).CancelIfRunning();
  48. QueueScheduledTask<T>(options);
  49. }
  50. /// <inheritdoc />
  51. public void CancelIfRunningAndQueue<T>()
  52. where T : IScheduledTask
  53. {
  54. CancelIfRunningAndQueue<T>(new TaskOptions());
  55. }
  56. /// <inheritdoc />
  57. public void CancelIfRunning<T>()
  58. where T : IScheduledTask
  59. {
  60. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  61. ((ScheduledTaskWorker)task).CancelIfRunning();
  62. }
  63. /// <inheritdoc />
  64. public void QueueScheduledTask<T>(TaskOptions options)
  65. where T : IScheduledTask
  66. {
  67. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  68. if (scheduledTask is null)
  69. {
  70. _logger.LogError("Unable to find scheduled task of type {Type} in QueueScheduledTask.", typeof(T).Name);
  71. }
  72. else
  73. {
  74. QueueScheduledTask(scheduledTask, options);
  75. }
  76. }
  77. /// <inheritdoc />
  78. public void QueueScheduledTask<T>()
  79. where T : IScheduledTask
  80. {
  81. QueueScheduledTask<T>(new TaskOptions());
  82. }
  83. /// <inheritdoc />
  84. public void QueueIfNotRunning<T>()
  85. where T : IScheduledTask
  86. {
  87. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  88. if (task.State != TaskState.Running)
  89. {
  90. QueueScheduledTask<T>(new TaskOptions());
  91. }
  92. }
  93. /// <inheritdoc />
  94. public void Execute<T>()
  95. where T : IScheduledTask
  96. {
  97. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  98. if (scheduledTask is null)
  99. {
  100. _logger.LogError("Unable to find scheduled task of type {Type} in Execute.", typeof(T).Name);
  101. }
  102. else
  103. {
  104. var type = scheduledTask.ScheduledTask.GetType();
  105. _logger.LogDebug("Queuing task {Name}", type.Name);
  106. lock (_taskQueue)
  107. {
  108. if (scheduledTask.State == TaskState.Idle)
  109. {
  110. Execute(scheduledTask, new TaskOptions());
  111. }
  112. }
  113. }
  114. }
  115. /// <inheritdoc />
  116. public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
  117. {
  118. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  119. if (scheduledTask is null)
  120. {
  121. _logger.LogError("Unable to find scheduled task of type {Type} 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, TaskOptions options)
  134. {
  135. var type = task.ScheduledTask.GetType();
  136. _logger.LogDebug("Queuing task {Name}", 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, TaskOptions>(type, options));
  145. }
  146. }
  147. /// <inheritdoc />
  148. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  149. {
  150. var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _logger));
  151. ScheduledTasks = ScheduledTasks.Concat(list).ToArray();
  152. }
  153. /// <inheritdoc />
  154. public void Dispose()
  155. {
  156. Dispose(true);
  157. GC.SuppressFinalize(this);
  158. }
  159. /// <summary>
  160. /// Releases unmanaged and - optionally - managed resources.
  161. /// </summary>
  162. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  163. protected virtual void Dispose(bool dispose)
  164. {
  165. foreach (var task in ScheduledTasks)
  166. {
  167. task.Dispose();
  168. }
  169. }
  170. /// <inheritdoc />
  171. public void Cancel(IScheduledTaskWorker task)
  172. {
  173. ((ScheduledTaskWorker)task).Cancel();
  174. }
  175. /// <inheritdoc />
  176. public Task Execute(IScheduledTaskWorker task, TaskOptions options)
  177. {
  178. return ((ScheduledTaskWorker)task).Execute(options);
  179. }
  180. /// <summary>
  181. /// Called when [task executing].
  182. /// </summary>
  183. /// <param name="task">The task.</param>
  184. internal void OnTaskExecuting(IScheduledTaskWorker task)
  185. {
  186. TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>(task));
  187. }
  188. /// <summary>
  189. /// Called when [task completed].
  190. /// </summary>
  191. /// <param name="task">The task.</param>
  192. /// <param name="result">The result.</param>
  193. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  194. {
  195. TaskCompleted?.Invoke(task, new TaskCompletionEventArgs(task, result));
  196. ExecuteQueuedTasks();
  197. }
  198. /// <summary>
  199. /// Executes the queued tasks.
  200. /// </summary>
  201. private void ExecuteQueuedTasks()
  202. {
  203. lock (_taskQueue)
  204. {
  205. var list = new List<Tuple<Type, TaskOptions>>();
  206. while (_taskQueue.TryDequeue(out var item))
  207. {
  208. if (list.All(i => i.Item1 != item.Item1))
  209. {
  210. list.Add(item);
  211. }
  212. }
  213. foreach (var enqueuedType in list)
  214. {
  215. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
  216. if (scheduledTask.State == TaskState.Idle)
  217. {
  218. Execute(scheduledTask, enqueuedType.Item2);
  219. }
  220. }
  221. }
  222. }
  223. }