TaskManager.cs 11 KB

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