2
0

TaskManager.cs 12 KB

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