ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Extensions;
  9. using MediaBrowser.Common.Progress;
  10. using MediaBrowser.Model.Events;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Serialization;
  13. using MediaBrowser.Model.Tasks;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Server.Implementations.ScheduledTasks
  16. {
  17. /// <summary>
  18. /// Class ScheduledTaskWorker
  19. /// </summary>
  20. public class ScheduledTaskWorker : IScheduledTaskWorker
  21. {
  22. public event EventHandler<GenericEventArgs<double>> TaskProgress;
  23. /// <summary>
  24. /// Gets the scheduled task.
  25. /// </summary>
  26. /// <value>The scheduled task.</value>
  27. public IScheduledTask ScheduledTask { get; private set; }
  28. /// <summary>
  29. /// Gets or sets the json serializer.
  30. /// </summary>
  31. /// <value>The json serializer.</value>
  32. private IJsonSerializer JsonSerializer { get; set; }
  33. /// <summary>
  34. /// Gets or sets the application paths.
  35. /// </summary>
  36. /// <value>The application paths.</value>
  37. private IApplicationPaths ApplicationPaths { get; set; }
  38. /// <summary>
  39. /// Gets the logger.
  40. /// </summary>
  41. /// <value>The logger.</value>
  42. private ILogger Logger { get; set; }
  43. /// <summary>
  44. /// Gets the task manager.
  45. /// </summary>
  46. /// <value>The task manager.</value>
  47. private ITaskManager TaskManager { get; set; }
  48. private readonly IFileSystem _fileSystem;
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
  51. /// </summary>
  52. /// <param name="scheduledTask">The scheduled task.</param>
  53. /// <param name="applicationPaths">The application paths.</param>
  54. /// <param name="taskManager">The task manager.</param>
  55. /// <param name="jsonSerializer">The json serializer.</param>
  56. /// <param name="logger">The logger.</param>
  57. /// <exception cref="ArgumentNullException">
  58. /// scheduledTask
  59. /// or
  60. /// applicationPaths
  61. /// or
  62. /// taskManager
  63. /// or
  64. /// jsonSerializer
  65. /// or
  66. /// logger
  67. /// </exception>
  68. public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem)
  69. {
  70. if (scheduledTask == null)
  71. {
  72. throw new ArgumentNullException(nameof(scheduledTask));
  73. }
  74. if (applicationPaths == null)
  75. {
  76. throw new ArgumentNullException(nameof(applicationPaths));
  77. }
  78. if (taskManager == null)
  79. {
  80. throw new ArgumentNullException(nameof(taskManager));
  81. }
  82. if (jsonSerializer == null)
  83. {
  84. throw new ArgumentNullException(nameof(jsonSerializer));
  85. }
  86. if (logger == null)
  87. {
  88. throw new ArgumentNullException(nameof(logger));
  89. }
  90. ScheduledTask = scheduledTask;
  91. ApplicationPaths = applicationPaths;
  92. TaskManager = taskManager;
  93. JsonSerializer = jsonSerializer;
  94. Logger = logger;
  95. _fileSystem = fileSystem;
  96. InitTriggerEvents();
  97. }
  98. private bool _readFromFile = false;
  99. /// <summary>
  100. /// The _last execution result
  101. /// </summary>
  102. private TaskResult _lastExecutionResult;
  103. /// <summary>
  104. /// The _last execution result sync lock
  105. /// </summary>
  106. private readonly object _lastExecutionResultSyncLock = new object();
  107. /// <summary>
  108. /// Gets the last execution result.
  109. /// </summary>
  110. /// <value>The last execution result.</value>
  111. public TaskResult LastExecutionResult
  112. {
  113. get
  114. {
  115. var path = GetHistoryFilePath();
  116. lock (_lastExecutionResultSyncLock)
  117. {
  118. if (_lastExecutionResult == null && !_readFromFile)
  119. {
  120. if (File.Exists(path))
  121. {
  122. try
  123. {
  124. _lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path);
  125. }
  126. catch (Exception ex)
  127. {
  128. Logger.LogError(ex, "Error deserializing {File}", path);
  129. }
  130. }
  131. _readFromFile = true;
  132. }
  133. }
  134. return _lastExecutionResult;
  135. }
  136. private set
  137. {
  138. _lastExecutionResult = value;
  139. var path = GetHistoryFilePath();
  140. Directory.CreateDirectory(Path.GetDirectoryName(path));
  141. lock (_lastExecutionResultSyncLock)
  142. {
  143. JsonSerializer.SerializeToFile(value, path);
  144. }
  145. }
  146. }
  147. /// <summary>
  148. /// Gets the name.
  149. /// </summary>
  150. /// <value>The name.</value>
  151. public string Name => ScheduledTask.Name;
  152. /// <summary>
  153. /// Gets the description.
  154. /// </summary>
  155. /// <value>The description.</value>
  156. public string Description => ScheduledTask.Description;
  157. /// <summary>
  158. /// Gets the category.
  159. /// </summary>
  160. /// <value>The category.</value>
  161. public string Category => ScheduledTask.Category;
  162. /// <summary>
  163. /// Gets the current cancellation token
  164. /// </summary>
  165. /// <value>The current cancellation token source.</value>
  166. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  167. /// <summary>
  168. /// Gets or sets the current execution start time.
  169. /// </summary>
  170. /// <value>The current execution start time.</value>
  171. private DateTime CurrentExecutionStartTime { get; set; }
  172. /// <summary>
  173. /// Gets the state.
  174. /// </summary>
  175. /// <value>The state.</value>
  176. public TaskState State
  177. {
  178. get
  179. {
  180. if (CurrentCancellationTokenSource != null)
  181. {
  182. return CurrentCancellationTokenSource.IsCancellationRequested
  183. ? TaskState.Cancelling
  184. : TaskState.Running;
  185. }
  186. return TaskState.Idle;
  187. }
  188. }
  189. /// <summary>
  190. /// Gets the current progress.
  191. /// </summary>
  192. /// <value>The current progress.</value>
  193. public double? CurrentProgress { get; private set; }
  194. /// <summary>
  195. /// The _triggers.
  196. /// </summary>
  197. private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
  198. /// <summary>
  199. /// Gets the triggers that define when the task will run.
  200. /// </summary>
  201. /// <value>The triggers.</value>
  202. private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
  203. {
  204. get => _triggers;
  205. set
  206. {
  207. if (value == null)
  208. {
  209. throw new ArgumentNullException(nameof(value));
  210. }
  211. // Cleanup current triggers
  212. if (_triggers != null)
  213. {
  214. DisposeTriggers();
  215. }
  216. _triggers = value.ToArray();
  217. ReloadTriggerEvents(false);
  218. }
  219. }
  220. /// <summary>
  221. /// Gets the triggers that define when the task will run.
  222. /// </summary>
  223. /// <value>The triggers.</value>
  224. /// <exception cref="ArgumentNullException">value</exception>
  225. public TaskTriggerInfo[] Triggers
  226. {
  227. get
  228. {
  229. var triggers = InternalTriggers;
  230. return triggers.Select(i => i.Item1).ToArray();
  231. }
  232. set
  233. {
  234. if (value == null)
  235. {
  236. throw new ArgumentNullException(nameof(value));
  237. }
  238. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  239. var triggerList = value.Where(i => i != null).ToArray();
  240. SaveTriggers(triggerList);
  241. InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  242. }
  243. }
  244. /// <summary>
  245. /// The _id
  246. /// </summary>
  247. private string _id;
  248. /// <summary>
  249. /// Gets the unique id.
  250. /// </summary>
  251. /// <value>The unique id.</value>
  252. public string Id
  253. {
  254. get
  255. {
  256. if (_id == null)
  257. {
  258. _id = ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  259. }
  260. return _id;
  261. }
  262. }
  263. private void InitTriggerEvents()
  264. {
  265. _triggers = LoadTriggers();
  266. ReloadTriggerEvents(true);
  267. }
  268. public void ReloadTriggerEvents()
  269. {
  270. ReloadTriggerEvents(false);
  271. }
  272. /// <summary>
  273. /// Reloads the trigger events.
  274. /// </summary>
  275. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  276. private void ReloadTriggerEvents(bool isApplicationStartup)
  277. {
  278. foreach (var triggerInfo in InternalTriggers)
  279. {
  280. var trigger = triggerInfo.Item2;
  281. trigger.Stop();
  282. trigger.Triggered -= trigger_Triggered;
  283. trigger.Triggered += trigger_Triggered;
  284. trigger.Start(LastExecutionResult, Logger, Name, isApplicationStartup);
  285. }
  286. }
  287. /// <summary>
  288. /// Handles the Triggered event of the trigger control.
  289. /// </summary>
  290. /// <param name="sender">The source of the event.</param>
  291. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  292. async void trigger_Triggered(object sender, EventArgs e)
  293. {
  294. var trigger = (ITaskTrigger)sender;
  295. var configurableTask = ScheduledTask as IConfigurableScheduledTask;
  296. if (configurableTask != null && !configurableTask.IsEnabled)
  297. {
  298. return;
  299. }
  300. Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name);
  301. trigger.Stop();
  302. TaskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
  303. await Task.Delay(1000).ConfigureAwait(false);
  304. trigger.Start(LastExecutionResult, Logger, Name, false);
  305. }
  306. private Task _currentTask;
  307. /// <summary>
  308. /// Executes the task
  309. /// </summary>
  310. /// <param name="options">Task options.</param>
  311. /// <returns>Task.</returns>
  312. /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running</exception>
  313. public async Task Execute(TaskOptions options)
  314. {
  315. var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
  316. _currentTask = task;
  317. try
  318. {
  319. await task.ConfigureAwait(false);
  320. }
  321. finally
  322. {
  323. _currentTask = null;
  324. GC.Collect();
  325. }
  326. }
  327. private async Task ExecuteInternal(TaskOptions options)
  328. {
  329. // Cancel the current execution, if any
  330. if (CurrentCancellationTokenSource != null)
  331. {
  332. throw new InvalidOperationException("Cannot execute a Task that is already running");
  333. }
  334. var progress = new SimpleProgress<double>();
  335. CurrentCancellationTokenSource = new CancellationTokenSource();
  336. Logger.LogInformation("Executing {0}", Name);
  337. ((TaskManager)TaskManager).OnTaskExecuting(this);
  338. progress.ProgressChanged += progress_ProgressChanged;
  339. TaskCompletionStatus status;
  340. CurrentExecutionStartTime = DateTime.UtcNow;
  341. Exception failureException = null;
  342. try
  343. {
  344. if (options != null && options.MaxRuntimeTicks.HasValue)
  345. {
  346. CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
  347. }
  348. await ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false);
  349. status = TaskCompletionStatus.Completed;
  350. }
  351. catch (OperationCanceledException)
  352. {
  353. status = TaskCompletionStatus.Cancelled;
  354. }
  355. catch (Exception ex)
  356. {
  357. Logger.LogError(ex, "Error");
  358. failureException = ex;
  359. status = TaskCompletionStatus.Failed;
  360. }
  361. var startTime = CurrentExecutionStartTime;
  362. var endTime = DateTime.UtcNow;
  363. progress.ProgressChanged -= progress_ProgressChanged;
  364. CurrentCancellationTokenSource.Dispose();
  365. CurrentCancellationTokenSource = null;
  366. CurrentProgress = null;
  367. OnTaskCompleted(startTime, endTime, status, failureException);
  368. }
  369. /// <summary>
  370. /// Progress_s the progress changed.
  371. /// </summary>
  372. /// <param name="sender">The sender.</param>
  373. /// <param name="e">The e.</param>
  374. void progress_ProgressChanged(object sender, double e)
  375. {
  376. e = Math.Min(e, 100);
  377. CurrentProgress = e;
  378. TaskProgress?.Invoke(this, new GenericEventArgs<double>
  379. {
  380. Argument = e
  381. });
  382. }
  383. /// <summary>
  384. /// Stops the task if it is currently executing
  385. /// </summary>
  386. /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  387. public void Cancel()
  388. {
  389. if (State != TaskState.Running)
  390. {
  391. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  392. }
  393. CancelIfRunning();
  394. }
  395. /// <summary>
  396. /// Cancels if running.
  397. /// </summary>
  398. public void CancelIfRunning()
  399. {
  400. if (State == TaskState.Running)
  401. {
  402. Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
  403. CurrentCancellationTokenSource.Cancel();
  404. }
  405. }
  406. /// <summary>
  407. /// Gets the scheduled tasks configuration directory.
  408. /// </summary>
  409. /// <returns>System.String.</returns>
  410. private string GetScheduledTasksConfigurationDirectory()
  411. {
  412. return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  413. }
  414. /// <summary>
  415. /// Gets the scheduled tasks data directory.
  416. /// </summary>
  417. /// <returns>System.String.</returns>
  418. private string GetScheduledTasksDataDirectory()
  419. {
  420. return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
  421. }
  422. /// <summary>
  423. /// Gets the history file path.
  424. /// </summary>
  425. /// <value>The history file path.</value>
  426. private string GetHistoryFilePath()
  427. {
  428. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  429. }
  430. /// <summary>
  431. /// Gets the configuration file path.
  432. /// </summary>
  433. /// <returns>System.String.</returns>
  434. private string GetConfigurationFilePath()
  435. {
  436. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  437. }
  438. /// <summary>
  439. /// Loads the triggers.
  440. /// </summary>
  441. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  442. private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
  443. {
  444. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  445. var settings = LoadTriggerSettings().Where(i => i != null).ToArray();
  446. return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  447. }
  448. private TaskTriggerInfo[] LoadTriggerSettings()
  449. {
  450. string path = GetConfigurationFilePath();
  451. TaskTriggerInfo[] list = null;
  452. if (File.Exists(path))
  453. {
  454. list = JsonSerializer.DeserializeFromFile<TaskTriggerInfo[]>(path);
  455. }
  456. // Return defaults if file doesn't exist.
  457. return list ?? GetDefaultTriggers();
  458. }
  459. private TaskTriggerInfo[] GetDefaultTriggers()
  460. {
  461. try
  462. {
  463. return ScheduledTask.GetDefaultTriggers().ToArray();
  464. }
  465. catch
  466. {
  467. return new TaskTriggerInfo[]
  468. {
  469. new TaskTriggerInfo
  470. {
  471. IntervalTicks = TimeSpan.FromDays(1).Ticks,
  472. Type = TaskTriggerInfo.TriggerInterval
  473. }
  474. };
  475. }
  476. }
  477. /// <summary>
  478. /// Saves the triggers.
  479. /// </summary>
  480. /// <param name="triggers">The triggers.</param>
  481. private void SaveTriggers(TaskTriggerInfo[] triggers)
  482. {
  483. var path = GetConfigurationFilePath();
  484. Directory.CreateDirectory(Path.GetDirectoryName(path));
  485. JsonSerializer.SerializeToFile(triggers, path);
  486. }
  487. /// <summary>
  488. /// Called when [task completed].
  489. /// </summary>
  490. /// <param name="startTime">The start time.</param>
  491. /// <param name="endTime">The end time.</param>
  492. /// <param name="status">The status.</param>
  493. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  494. {
  495. var elapsedTime = endTime - startTime;
  496. Logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  497. var result = new TaskResult
  498. {
  499. StartTimeUtc = startTime,
  500. EndTimeUtc = endTime,
  501. Status = status,
  502. Name = Name,
  503. Id = Id
  504. };
  505. result.Key = ScheduledTask.Key;
  506. if (ex != null)
  507. {
  508. result.ErrorMessage = ex.Message;
  509. result.LongErrorMessage = ex.StackTrace;
  510. }
  511. LastExecutionResult = result;
  512. ((TaskManager)TaskManager).OnTaskCompleted(this, result);
  513. }
  514. /// <summary>
  515. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  516. /// </summary>
  517. public void Dispose()
  518. {
  519. Dispose(true);
  520. }
  521. /// <summary>
  522. /// Releases unmanaged and - optionally - managed resources.
  523. /// </summary>
  524. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  525. protected virtual void Dispose(bool dispose)
  526. {
  527. if (dispose)
  528. {
  529. DisposeTriggers();
  530. var wassRunning = State == TaskState.Running;
  531. var startTime = CurrentExecutionStartTime;
  532. var token = CurrentCancellationTokenSource;
  533. if (token != null)
  534. {
  535. try
  536. {
  537. Logger.LogInformation(Name + ": Cancelling");
  538. token.Cancel();
  539. }
  540. catch (Exception ex)
  541. {
  542. Logger.LogError(ex, "Error calling CancellationToken.Cancel();");
  543. }
  544. }
  545. var task = _currentTask;
  546. if (task != null)
  547. {
  548. try
  549. {
  550. Logger.LogInformation(Name + ": Waiting on Task");
  551. var exited = Task.WaitAll(new[] { task }, 2000);
  552. if (exited)
  553. {
  554. Logger.LogInformation(Name + ": Task exited");
  555. }
  556. else
  557. {
  558. Logger.LogInformation(Name + ": Timed out waiting for task to stop");
  559. }
  560. }
  561. catch (Exception ex)
  562. {
  563. Logger.LogError(ex, "Error calling Task.WaitAll();");
  564. }
  565. }
  566. if (token != null)
  567. {
  568. try
  569. {
  570. Logger.LogDebug(Name + ": Disposing CancellationToken");
  571. token.Dispose();
  572. }
  573. catch (Exception ex)
  574. {
  575. Logger.LogError(ex, "Error calling CancellationToken.Dispose();");
  576. }
  577. }
  578. if (wassRunning)
  579. {
  580. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  581. }
  582. }
  583. }
  584. /// <summary>
  585. /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger
  586. /// </summary>
  587. /// <param name="info">The info.</param>
  588. /// <returns>BaseTaskTrigger.</returns>
  589. /// <exception cref="ArgumentNullException"></exception>
  590. /// <exception cref="ArgumentException">Invalid trigger type: + info.Type</exception>
  591. private ITaskTrigger GetTrigger(TaskTriggerInfo info)
  592. {
  593. var options = new TaskOptions
  594. {
  595. MaxRuntimeTicks = info.MaxRuntimeTicks
  596. };
  597. if (info.Type.Equals(typeof(DailyTrigger).Name, StringComparison.OrdinalIgnoreCase))
  598. {
  599. if (!info.TimeOfDayTicks.HasValue)
  600. {
  601. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  602. }
  603. return new DailyTrigger
  604. {
  605. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  606. TaskOptions = options
  607. };
  608. }
  609. if (info.Type.Equals(typeof(WeeklyTrigger).Name, StringComparison.OrdinalIgnoreCase))
  610. {
  611. if (!info.TimeOfDayTicks.HasValue)
  612. {
  613. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  614. }
  615. if (!info.DayOfWeek.HasValue)
  616. {
  617. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  618. }
  619. return new WeeklyTrigger
  620. {
  621. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  622. DayOfWeek = info.DayOfWeek.Value,
  623. TaskOptions = options
  624. };
  625. }
  626. if (info.Type.Equals(typeof(IntervalTrigger).Name, StringComparison.OrdinalIgnoreCase))
  627. {
  628. if (!info.IntervalTicks.HasValue)
  629. {
  630. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  631. }
  632. return new IntervalTrigger
  633. {
  634. Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
  635. TaskOptions = options
  636. };
  637. }
  638. if (info.Type.Equals(typeof(StartupTrigger).Name, StringComparison.OrdinalIgnoreCase))
  639. {
  640. return new StartupTrigger();
  641. }
  642. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  643. }
  644. /// <summary>
  645. /// Disposes each trigger
  646. /// </summary>
  647. private void DisposeTriggers()
  648. {
  649. foreach (var triggerInfo in InternalTriggers)
  650. {
  651. var trigger = triggerInfo.Item2;
  652. trigger.Triggered -= trigger_Triggered;
  653. trigger.Stop();
  654. }
  655. }
  656. }
  657. }