ScheduledTaskWorker.cs 25 KB

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