TaskManager.cs 9.7 KB

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