TaskManager.cs 11 KB

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