TaskManager.cs 9.0 KB

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