TaskManager.cs 10.0 KB

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