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. BindToSystemEvent();
  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. }
  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. }