ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. var triggers = InternalTriggers;
  223. return triggers.Select(i => i.Item1).ToArray();
  224. }
  225. set
  226. {
  227. ArgumentNullException.ThrowIfNull(value);
  228. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  229. var triggerList = value.Where(i => i is not null).ToArray();
  230. SaveTriggers(triggerList);
  231. InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  232. }
  233. }
  234. /// <summary>
  235. /// Gets the unique id.
  236. /// </summary>
  237. /// <value>The unique id.</value>
  238. public string Id
  239. {
  240. get
  241. {
  242. return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  243. }
  244. }
  245. private void InitTriggerEvents()
  246. {
  247. _triggers = LoadTriggers();
  248. ReloadTriggerEvents(true);
  249. }
  250. public void ReloadTriggerEvents()
  251. {
  252. ReloadTriggerEvents(false);
  253. }
  254. /// <summary>
  255. /// Reloads the trigger events.
  256. /// </summary>
  257. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  258. private void ReloadTriggerEvents(bool isApplicationStartup)
  259. {
  260. foreach (var triggerInfo in InternalTriggers)
  261. {
  262. var trigger = triggerInfo.Item2;
  263. trigger.Stop();
  264. trigger.Triggered -= OnTriggerTriggered;
  265. trigger.Triggered += OnTriggerTriggered;
  266. trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
  267. }
  268. }
  269. /// <summary>
  270. /// Handles the Triggered event of the trigger control.
  271. /// </summary>
  272. /// <param name="sender">The source of the event.</param>
  273. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  274. private async void OnTriggerTriggered(object sender, EventArgs e)
  275. {
  276. var trigger = (ITaskTrigger)sender;
  277. if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
  278. {
  279. return;
  280. }
  281. _logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name);
  282. trigger.Stop();
  283. _taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
  284. await Task.Delay(1000).ConfigureAwait(false);
  285. trigger.Start(LastExecutionResult, _logger, Name, false);
  286. }
  287. /// <summary>
  288. /// Executes the task.
  289. /// </summary>
  290. /// <param name="options">Task options.</param>
  291. /// <returns>Task.</returns>
  292. /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running.</exception>
  293. public async Task Execute(TaskOptions options)
  294. {
  295. var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
  296. _currentTask = task;
  297. try
  298. {
  299. await task.ConfigureAwait(false);
  300. }
  301. finally
  302. {
  303. _currentTask = null;
  304. GC.Collect();
  305. }
  306. }
  307. private async Task ExecuteInternal(TaskOptions options)
  308. {
  309. // Cancel the current execution, if any
  310. if (CurrentCancellationTokenSource is not null)
  311. {
  312. throw new InvalidOperationException("Cannot execute a Task that is already running");
  313. }
  314. var progress = new Progress<double>();
  315. CurrentCancellationTokenSource = new CancellationTokenSource();
  316. _logger.LogDebug("Executing {0}", Name);
  317. ((TaskManager)_taskManager).OnTaskExecuting(this);
  318. progress.ProgressChanged += OnProgressChanged;
  319. TaskCompletionStatus status;
  320. CurrentExecutionStartTime = DateTime.UtcNow;
  321. Exception failureException = null;
  322. try
  323. {
  324. if (options is not null && options.MaxRuntimeTicks.HasValue)
  325. {
  326. CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
  327. }
  328. await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false);
  329. status = TaskCompletionStatus.Completed;
  330. }
  331. catch (OperationCanceledException)
  332. {
  333. status = TaskCompletionStatus.Cancelled;
  334. }
  335. catch (Exception ex)
  336. {
  337. _logger.LogError(ex, "Error executing Scheduled Task");
  338. failureException = ex;
  339. status = TaskCompletionStatus.Failed;
  340. }
  341. var startTime = CurrentExecutionStartTime;
  342. var endTime = DateTime.UtcNow;
  343. progress.ProgressChanged -= OnProgressChanged;
  344. CurrentCancellationTokenSource.Dispose();
  345. CurrentCancellationTokenSource = null;
  346. CurrentProgress = null;
  347. OnTaskCompleted(startTime, endTime, status, failureException);
  348. }
  349. /// <summary>
  350. /// Progress_s the progress changed.
  351. /// </summary>
  352. /// <param name="sender">The sender.</param>
  353. /// <param name="e">The e.</param>
  354. private void OnProgressChanged(object sender, double e)
  355. {
  356. e = Math.Min(e, 100);
  357. CurrentProgress = e;
  358. TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
  359. }
  360. /// <summary>
  361. /// Stops the task if it is currently executing.
  362. /// </summary>
  363. /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  364. public void Cancel()
  365. {
  366. if (State != TaskState.Running)
  367. {
  368. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  369. }
  370. CancelIfRunning();
  371. }
  372. /// <summary>
  373. /// Cancels if running.
  374. /// </summary>
  375. public void CancelIfRunning()
  376. {
  377. if (State == TaskState.Running)
  378. {
  379. _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
  380. CurrentCancellationTokenSource.Cancel();
  381. }
  382. }
  383. /// <summary>
  384. /// Gets the scheduled tasks configuration directory.
  385. /// </summary>
  386. /// <returns>System.String.</returns>
  387. private string GetScheduledTasksConfigurationDirectory()
  388. {
  389. return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  390. }
  391. /// <summary>
  392. /// Gets the scheduled tasks data directory.
  393. /// </summary>
  394. /// <returns>System.String.</returns>
  395. private string GetScheduledTasksDataDirectory()
  396. {
  397. return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
  398. }
  399. /// <summary>
  400. /// Gets the history file path.
  401. /// </summary>
  402. /// <value>The history file path.</value>
  403. private string GetHistoryFilePath()
  404. {
  405. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  406. }
  407. /// <summary>
  408. /// Gets the configuration file path.
  409. /// </summary>
  410. /// <returns>System.String.</returns>
  411. private string GetConfigurationFilePath()
  412. {
  413. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  414. }
  415. /// <summary>
  416. /// Loads the triggers.
  417. /// </summary>
  418. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  419. private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
  420. {
  421. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  422. var settings = LoadTriggerSettings().Where(i => i is not null).ToArray();
  423. return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  424. }
  425. private TaskTriggerInfo[] LoadTriggerSettings()
  426. {
  427. string path = GetConfigurationFilePath();
  428. TaskTriggerInfo[] list = null;
  429. if (File.Exists(path))
  430. {
  431. var bytes = File.ReadAllBytes(path);
  432. list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
  433. }
  434. // Return defaults if file doesn't exist.
  435. return list ?? GetDefaultTriggers();
  436. }
  437. private TaskTriggerInfo[] GetDefaultTriggers()
  438. {
  439. try
  440. {
  441. return ScheduledTask.GetDefaultTriggers().ToArray();
  442. }
  443. catch
  444. {
  445. return new TaskTriggerInfo[]
  446. {
  447. new TaskTriggerInfo
  448. {
  449. IntervalTicks = TimeSpan.FromDays(1).Ticks,
  450. Type = TaskTriggerInfo.TriggerInterval
  451. }
  452. };
  453. }
  454. }
  455. /// <summary>
  456. /// Saves the triggers.
  457. /// </summary>
  458. /// <param name="triggers">The triggers.</param>
  459. private void SaveTriggers(TaskTriggerInfo[] triggers)
  460. {
  461. var path = GetConfigurationFilePath();
  462. Directory.CreateDirectory(Path.GetDirectoryName(path));
  463. using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  464. using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
  465. JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
  466. }
  467. /// <summary>
  468. /// Called when [task completed].
  469. /// </summary>
  470. /// <param name="startTime">The start time.</param>
  471. /// <param name="endTime">The end time.</param>
  472. /// <param name="status">The status.</param>
  473. /// <param name="ex">The exception.</param>
  474. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  475. {
  476. var elapsedTime = endTime - startTime;
  477. _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  478. var result = new TaskResult
  479. {
  480. StartTimeUtc = startTime,
  481. EndTimeUtc = endTime,
  482. Status = status,
  483. Name = Name,
  484. Id = Id
  485. };
  486. result.Key = ScheduledTask.Key;
  487. if (ex is not null)
  488. {
  489. result.ErrorMessage = ex.Message;
  490. result.LongErrorMessage = ex.StackTrace;
  491. }
  492. LastExecutionResult = result;
  493. ((TaskManager)_taskManager).OnTaskCompleted(this, result);
  494. }
  495. /// <summary>
  496. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  497. /// </summary>
  498. public void Dispose()
  499. {
  500. Dispose(true);
  501. GC.SuppressFinalize(this);
  502. }
  503. /// <summary>
  504. /// Releases unmanaged and - optionally - managed resources.
  505. /// </summary>
  506. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  507. protected virtual void Dispose(bool dispose)
  508. {
  509. if (dispose)
  510. {
  511. DisposeTriggers();
  512. var wassRunning = State == TaskState.Running;
  513. var startTime = CurrentExecutionStartTime;
  514. var token = CurrentCancellationTokenSource;
  515. if (token is not null)
  516. {
  517. try
  518. {
  519. _logger.LogInformation("{Name}: Cancelling", Name);
  520. token.Cancel();
  521. }
  522. catch (Exception ex)
  523. {
  524. _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
  525. }
  526. }
  527. var task = _currentTask;
  528. if (task is not null)
  529. {
  530. try
  531. {
  532. _logger.LogInformation("{Name}: Waiting on Task", Name);
  533. var exited = task.Wait(2000);
  534. if (exited)
  535. {
  536. _logger.LogInformation("{Name}: Task exited", Name);
  537. }
  538. else
  539. {
  540. _logger.LogInformation("{Name}: Timed out waiting for task to stop", Name);
  541. }
  542. }
  543. catch (Exception ex)
  544. {
  545. _logger.LogError(ex, "Error calling Task.WaitAll();");
  546. }
  547. }
  548. if (token is not null)
  549. {
  550. try
  551. {
  552. _logger.LogDebug("{Name}: Disposing CancellationToken", Name);
  553. token.Dispose();
  554. }
  555. catch (Exception ex)
  556. {
  557. _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
  558. }
  559. }
  560. if (wassRunning)
  561. {
  562. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  563. }
  564. }
  565. }
  566. /// <summary>
  567. /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
  568. /// </summary>
  569. /// <param name="info">The info.</param>
  570. /// <returns>BaseTaskTrigger.</returns>
  571. /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
  572. private ITaskTrigger GetTrigger(TaskTriggerInfo info)
  573. {
  574. var options = new TaskOptions
  575. {
  576. MaxRuntimeTicks = info.MaxRuntimeTicks
  577. };
  578. if (info.Type.Equals(nameof(DailyTrigger), StringComparison.OrdinalIgnoreCase))
  579. {
  580. if (!info.TimeOfDayTicks.HasValue)
  581. {
  582. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  583. }
  584. return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
  585. }
  586. if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
  587. {
  588. if (!info.TimeOfDayTicks.HasValue)
  589. {
  590. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  591. }
  592. if (!info.DayOfWeek.HasValue)
  593. {
  594. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  595. }
  596. return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
  597. }
  598. if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
  599. {
  600. if (!info.IntervalTicks.HasValue)
  601. {
  602. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  603. }
  604. return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
  605. }
  606. if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
  607. {
  608. return new StartupTrigger(options);
  609. }
  610. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  611. }
  612. /// <summary>
  613. /// Disposes each trigger.
  614. /// </summary>
  615. private void DisposeTriggers()
  616. {
  617. foreach (var triggerInfo in InternalTriggers)
  618. {
  619. var trigger = triggerInfo.Item2;
  620. trigger.Triggered -= OnTriggerTriggered;
  621. trigger.Stop();
  622. if (trigger is IDisposable disposable)
  623. {
  624. disposable.Dispose();
  625. }
  626. }
  627. }
  628. }
  629. }