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 MediaBrowser.Common.IO;
  14. using MediaBrowser.Model.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. }
  81. private void BindToSystemEvent()
  82. {
  83. try
  84. {
  85. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  86. }
  87. catch
  88. {
  89. }
  90. }
  91. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  92. {
  93. foreach (var task in ScheduledTasks)
  94. {
  95. task.ReloadTriggerEvents();
  96. }
  97. }
  98. /// <summary>
  99. /// Cancels if running and queue.
  100. /// </summary>
  101. /// <typeparam name="T"></typeparam>
  102. /// <param name="options">Task options.</param>
  103. public void CancelIfRunningAndQueue<T>(TaskExecutionOptions options)
  104. where T : IScheduledTask
  105. {
  106. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  107. ((ScheduledTaskWorker)task).CancelIfRunning();
  108. QueueScheduledTask<T>(options);
  109. }
  110. public void CancelIfRunningAndQueue<T>()
  111. where T : IScheduledTask
  112. {
  113. CancelIfRunningAndQueue<T>(new TaskExecutionOptions());
  114. }
  115. /// <summary>
  116. /// Cancels if running
  117. /// </summary>
  118. /// <typeparam name="T"></typeparam>
  119. public void CancelIfRunning<T>()
  120. where T : IScheduledTask
  121. {
  122. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  123. ((ScheduledTaskWorker)task).CancelIfRunning();
  124. }
  125. /// <summary>
  126. /// Queues the scheduled task.
  127. /// </summary>
  128. /// <typeparam name="T"></typeparam>
  129. /// <param name="options">Task options</param>
  130. public void QueueScheduledTask<T>(TaskExecutionOptions options)
  131. where T : IScheduledTask
  132. {
  133. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  134. if (scheduledTask == null)
  135. {
  136. Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
  137. }
  138. else
  139. {
  140. QueueScheduledTask(scheduledTask, options);
  141. }
  142. }
  143. public void QueueScheduledTask<T>()
  144. where T : IScheduledTask
  145. {
  146. QueueScheduledTask<T>(new TaskExecutionOptions());
  147. }
  148. public void QueueIfNotRunning<T>()
  149. where T : IScheduledTask
  150. {
  151. var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
  152. if (task.State != TaskState.Running)
  153. {
  154. QueueScheduledTask<T>(new TaskExecutionOptions());
  155. }
  156. }
  157. public void Execute<T>()
  158. where T : IScheduledTask
  159. {
  160. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
  161. if (scheduledTask == null)
  162. {
  163. Logger.Error("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
  164. }
  165. else
  166. {
  167. var type = scheduledTask.ScheduledTask.GetType();
  168. Logger.Info("Queueing task {0}", type.Name);
  169. lock (_taskQueue)
  170. {
  171. if (scheduledTask.State == TaskState.Idle)
  172. {
  173. Execute(scheduledTask, new TaskExecutionOptions());
  174. }
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// Queues the scheduled task.
  180. /// </summary>
  181. /// <param name="task">The task.</param>
  182. /// <param name="options">The task options.</param>
  183. public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
  184. {
  185. var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
  186. if (scheduledTask == null)
  187. {
  188. Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
  189. }
  190. else
  191. {
  192. QueueScheduledTask(scheduledTask, options);
  193. }
  194. }
  195. /// <summary>
  196. /// Queues the scheduled task.
  197. /// </summary>
  198. /// <param name="task">The task.</param>
  199. /// <param name="options">The task options.</param>
  200. private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
  201. {
  202. var type = task.ScheduledTask.GetType();
  203. Logger.Info("Queueing task {0}", type.Name);
  204. lock (_taskQueue)
  205. {
  206. if (task.State == TaskState.Idle && !SuspendTriggers)
  207. {
  208. Execute(task, options);
  209. return;
  210. }
  211. _taskQueue.Enqueue(new Tuple<Type, TaskExecutionOptions>(type, options));
  212. }
  213. }
  214. /// <summary>
  215. /// Adds the tasks.
  216. /// </summary>
  217. /// <param name="tasks">The tasks.</param>
  218. public void AddTasks(IEnumerable<IScheduledTask> tasks)
  219. {
  220. var myTasks = ScheduledTasks.ToList();
  221. var list = tasks.ToList();
  222. myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem)));
  223. ScheduledTasks = myTasks.ToArray();
  224. BindToSystemEvent();
  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. }