TaskManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 QueueIfNotRunning<T>()
  150. where T : IScheduledTask
  151. {
  152. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  153. if (task.State != TaskState.Running)
  154. {
  155. QueueScheduledTask<T>(new TaskExecutionOptions());
  156. }
  157. }
  158. public void Execute<T>()
  159. where T : IScheduledTask
  160. {
  161. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  162. if (scheduledTask == null)
  163. {
  164. Logger.Error("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
  165. }
  166. else
  167. {
  168. var type = scheduledTask.ScheduledTask.GetType();
  169. Logger.Info("Queueing task {0}", type.Name);
  170. lock (_taskQueue)
  171. {
  172. if (scheduledTask.State == TaskState.Idle)
  173. {
  174. Execute(scheduledTask, new TaskExecutionOptions());
  175. }
  176. }
  177. }
  178. }
  179. /// <summary>
  180. /// Queues the scheduled task.
  181. /// </summary>
  182. /// <param name="task">The task.</param>
  183. /// <param name="options">The task options.</param>
  184. public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
  185. {
  186. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  187. if (scheduledTask == null)
  188. {
  189. Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
  190. }
  191. else
  192. {
  193. QueueScheduledTask(scheduledTask, options);
  194. }
  195. }
  196. /// <summary>
  197. /// Queues the scheduled task.
  198. /// </summary>
  199. /// <param name="task">The task.</param>
  200. /// <param name="options">The task options.</param>
  201. private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
  202. {
  203. var type = task.ScheduledTask.GetType();
  204. Logger.Info("Queueing task {0}", type.Name);
  205. lock (_taskQueue)
  206. {
  207. if (task.State == TaskState.Idle && !SuspendTriggers)
  208. {
  209. Execute(task, options);
  210. return;
  211. }
  212. _taskQueue.Enqueue(new Tuple<Type, TaskExecutionOptions>(type, options));
  213. }
  214. }
  215. /// <summary>
  216. /// Adds the tasks.
  217. /// </summary>
  218. /// <param name="tasks">The tasks.</param>
  219. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  220. {
  221. var myTasks = ScheduledTasks.ToList();
  222. var list = tasks.ToList();
  223. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem)));
  224. ScheduledTasks = myTasks.ToArray();
  225. }
  226. /// <summary>
  227. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  228. /// </summary>
  229. public void Dispose()
  230. {
  231. Dispose(true);
  232. GC.SuppressFinalize(this);
  233. }
  234. /// <summary>
  235. /// Releases unmanaged and - optionally - managed resources.
  236. /// </summary>
  237. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  238. protected virtual void Dispose(bool dispose)
  239. {
  240. foreach (var task in ScheduledTasks)
  241. {
  242. task.Dispose();
  243. }
  244. }
  245. public void Cancel(IScheduledTaskWorker task)
  246. {
  247. ((ScheduledTaskWorker)task).Cancel();
  248. }
  249. public Task Execute(IScheduledTaskWorker task, TaskExecutionOptions options)
  250. {
  251. return ((ScheduledTaskWorker)task).Execute(options);
  252. }
  253. /// <summary>
  254. /// Called when [task executing].
  255. /// </summary>
  256. /// <param name="task">The task.</param>
  257. internal void OnTaskExecuting(IScheduledTaskWorker task)
  258. {
  259. EventHelper.FireEventIfNotNull(TaskExecuting, this, new GenericEventArgs<IScheduledTaskWorker>
  260. {
  261. Argument = task
  262. }, Logger);
  263. }
  264. /// <summary>
  265. /// Called when [task completed].
  266. /// </summary>
  267. /// <param name="task">The task.</param>
  268. /// <param name="result">The result.</param>
  269. internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
  270. {
  271. EventHelper.FireEventIfNotNull(TaskCompleted, task, new TaskCompletionEventArgs
  272. {
  273. Result = result,
  274. Task = task
  275. }, Logger);
  276. ExecuteQueuedTasks();
  277. }
  278. /// <summary>
  279. /// Executes the queued tasks.
  280. /// </summary>
  281. private void ExecuteQueuedTasks()
  282. {
  283. if (SuspendTriggers)
  284. {
  285. return;
  286. }
  287. Logger.Info("ExecuteQueuedTasks");
  288. // Execute queued tasks
  289. lock (_taskQueue)
  290. {
  291. var list = new List<Tuple<Type, TaskExecutionOptions>>();
  292. Tuple<Type, TaskExecutionOptions> item;
  293. while (_taskQueue.TryDequeue(out item))
  294. {
  295. if (list.All(i => i.Item1 != item.Item1))
  296. {
  297. list.Add(item);
  298. }
  299. }
  300. foreach (var enqueuedType in list)
  301. {
  302. var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
  303. if (scheduledTask.State == TaskState.Idle)
  304. {
  305. Execute(scheduledTask, enqueuedType.Item2);
  306. }
  307. }
  308. }
  309. }
  310. }
  311. }