ScheduledTaskWorker.cs 25 KB

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