ScheduledTaskWorker.cs 25 KB

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