TaskManager.cs 11 KB

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