TaskManager.cs 8.3 KB

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