TaskManager.cs 11 KB

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