ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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 Jellyfin.Data.Events;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Common.Extensions;
  13. using Jellyfin.Extensions.Json;
  14. using MediaBrowser.Common.Progress;
  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. /// Gets or sets the application paths.
  26. /// </summary>
  27. /// <value>The application paths.</value>
  28. private readonly IApplicationPaths _applicationPaths;
  29. /// <summary>
  30. /// Gets or sets the logger.
  31. /// </summary>
  32. /// <value>The logger.</value>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// Gets or sets the task manager.
  36. /// </summary>
  37. /// <value>The task manager.</value>
  38. private readonly ITaskManager _taskManager;
  39. /// <summary>
  40. /// The _last execution result sync lock.
  41. /// </summary>
  42. private readonly object _lastExecutionResultSyncLock = new object();
  43. private bool _readFromFile = false;
  44. /// <summary>
  45. /// The _last execution result.
  46. /// </summary>
  47. private TaskResult _lastExecutionResult;
  48. private Task _currentTask;
  49. /// <summary>
  50. /// The _triggers.
  51. /// </summary>
  52. private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
  53. /// <summary>
  54. /// The _id.
  55. /// </summary>
  56. private string _id;
  57. /// <summary>
  58. /// The options for the json Serializer.
  59. /// </summary>
  60. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  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. if (scheduledTask == null)
  82. {
  83. throw new ArgumentNullException(nameof(scheduledTask));
  84. }
  85. if (applicationPaths == null)
  86. {
  87. throw new ArgumentNullException(nameof(applicationPaths));
  88. }
  89. if (taskManager == null)
  90. {
  91. throw new ArgumentNullException(nameof(taskManager));
  92. }
  93. if (logger == null)
  94. {
  95. throw new ArgumentNullException(nameof(logger));
  96. }
  97. ScheduledTask = scheduledTask;
  98. _applicationPaths = applicationPaths;
  99. _taskManager = taskManager;
  100. _logger = logger;
  101. InitTriggerEvents();
  102. }
  103. public event EventHandler<GenericEventArgs<double>> TaskProgress;
  104. /// <summary>
  105. /// Gets the scheduled task.
  106. /// </summary>
  107. /// <value>The scheduled task.</value>
  108. public IScheduledTask ScheduledTask { get; private set; }
  109. /// <summary>
  110. /// Gets the last execution result.
  111. /// </summary>
  112. /// <value>The last execution result.</value>
  113. public TaskResult LastExecutionResult
  114. {
  115. get
  116. {
  117. var path = GetHistoryFilePath();
  118. lock (_lastExecutionResultSyncLock)
  119. {
  120. if (_lastExecutionResult == null && !_readFromFile)
  121. {
  122. if (File.Exists(path))
  123. {
  124. var bytes = File.ReadAllBytes(path);
  125. if (bytes.Length > 0)
  126. {
  127. try
  128. {
  129. _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
  130. }
  131. catch (JsonException ex)
  132. {
  133. _logger.LogError(ex, "Error deserializing {File}", path);
  134. }
  135. }
  136. else
  137. {
  138. _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
  139. }
  140. }
  141. _readFromFile = true;
  142. }
  143. }
  144. return _lastExecutionResult;
  145. }
  146. private set
  147. {
  148. _lastExecutionResult = value;
  149. var path = GetHistoryFilePath();
  150. Directory.CreateDirectory(Path.GetDirectoryName(path));
  151. lock (_lastExecutionResultSyncLock)
  152. {
  153. using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  154. using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
  155. JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Gets the name.
  161. /// </summary>
  162. /// <value>The name.</value>
  163. public string Name => ScheduledTask.Name;
  164. /// <summary>
  165. /// Gets the description.
  166. /// </summary>
  167. /// <value>The description.</value>
  168. public string Description => ScheduledTask.Description;
  169. /// <summary>
  170. /// Gets the category.
  171. /// </summary>
  172. /// <value>The category.</value>
  173. public string Category => ScheduledTask.Category;
  174. /// <summary>
  175. /// Gets or sets the current cancellation token.
  176. /// </summary>
  177. /// <value>The current cancellation token source.</value>
  178. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  179. /// <summary>
  180. /// Gets or sets the current execution start time.
  181. /// </summary>
  182. /// <value>The current execution start time.</value>
  183. private DateTime CurrentExecutionStartTime { get; set; }
  184. /// <summary>
  185. /// Gets the state.
  186. /// </summary>
  187. /// <value>The state.</value>
  188. public TaskState State
  189. {
  190. get
  191. {
  192. if (CurrentCancellationTokenSource != null)
  193. {
  194. return CurrentCancellationTokenSource.IsCancellationRequested
  195. ? TaskState.Cancelling
  196. : TaskState.Running;
  197. }
  198. return TaskState.Idle;
  199. }
  200. }
  201. /// <summary>
  202. /// Gets the current progress.
  203. /// </summary>
  204. /// <value>The current progress.</value>
  205. public double? CurrentProgress { get; private set; }
  206. /// <summary>
  207. /// Gets or sets the triggers that define when the task will run.
  208. /// </summary>
  209. /// <value>The triggers.</value>
  210. private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
  211. {
  212. get => _triggers;
  213. set
  214. {
  215. if (value == null)
  216. {
  217. throw new ArgumentNullException(nameof(value));
  218. }
  219. // Cleanup current triggers
  220. if (_triggers != null)
  221. {
  222. DisposeTriggers();
  223. }
  224. _triggers = value.ToArray();
  225. ReloadTriggerEvents(false);
  226. }
  227. }
  228. /// <summary>
  229. /// Gets the triggers that define when the task will run.
  230. /// </summary>
  231. /// <value>The triggers.</value>
  232. /// <exception cref="ArgumentNullException"><c>value</c> is <c>null</c>.</exception>
  233. public TaskTriggerInfo[] Triggers
  234. {
  235. get
  236. {
  237. var triggers = InternalTriggers;
  238. return triggers.Select(i => i.Item1).ToArray();
  239. }
  240. set
  241. {
  242. if (value == null)
  243. {
  244. throw new ArgumentNullException(nameof(value));
  245. }
  246. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  247. var triggerList = value.Where(i => i != null).ToArray();
  248. SaveTriggers(triggerList);
  249. InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  250. }
  251. }
  252. /// <summary>
  253. /// Gets the unique id.
  254. /// </summary>
  255. /// <value>The unique id.</value>
  256. public string Id
  257. {
  258. get
  259. {
  260. return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  261. }
  262. }
  263. private void InitTriggerEvents()
  264. {
  265. _triggers = LoadTriggers();
  266. ReloadTriggerEvents(true);
  267. }
  268. public void ReloadTriggerEvents()
  269. {
  270. ReloadTriggerEvents(false);
  271. }
  272. /// <summary>
  273. /// Reloads the trigger events.
  274. /// </summary>
  275. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  276. private void ReloadTriggerEvents(bool isApplicationStartup)
  277. {
  278. foreach (var triggerInfo in InternalTriggers)
  279. {
  280. var trigger = triggerInfo.Item2;
  281. trigger.Stop();
  282. trigger.Triggered -= OnTriggerTriggered;
  283. trigger.Triggered += OnTriggerTriggered;
  284. trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
  285. }
  286. }
  287. /// <summary>
  288. /// Handles the Triggered event of the trigger control.
  289. /// </summary>
  290. /// <param name="sender">The source of the event.</param>
  291. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  292. private async void OnTriggerTriggered(object sender, EventArgs e)
  293. {
  294. var trigger = (ITaskTrigger)sender;
  295. if (ScheduledTask is IConfigurableScheduledTask configurableTask && !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 bytes = File.ReadAllBytes(path);
  450. list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
  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 createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  482. using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
  483. JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
  484. }
  485. /// <summary>
  486. /// Called when [task completed].
  487. /// </summary>
  488. /// <param name="startTime">The start time.</param>
  489. /// <param name="endTime">The end time.</param>
  490. /// <param name="status">The status.</param>
  491. /// <param name="ex">The exception.</param>
  492. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  493. {
  494. var elapsedTime = endTime - startTime;
  495. _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  496. var result = new TaskResult
  497. {
  498. StartTimeUtc = startTime,
  499. EndTimeUtc = endTime,
  500. Status = status,
  501. Name = Name,
  502. Id = Id
  503. };
  504. result.Key = ScheduledTask.Key;
  505. if (ex != null)
  506. {
  507. result.ErrorMessage = ex.Message;
  508. result.LongErrorMessage = ex.StackTrace;
  509. }
  510. LastExecutionResult = result;
  511. ((TaskManager)_taskManager).OnTaskCompleted(this, result);
  512. }
  513. /// <summary>
  514. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  515. /// </summary>
  516. public void Dispose()
  517. {
  518. Dispose(true);
  519. GC.SuppressFinalize(this);
  520. }
  521. /// <summary>
  522. /// Releases unmanaged and - optionally - managed resources.
  523. /// </summary>
  524. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  525. protected virtual void Dispose(bool dispose)
  526. {
  527. if (dispose)
  528. {
  529. DisposeTriggers();
  530. var wassRunning = State == TaskState.Running;
  531. var startTime = CurrentExecutionStartTime;
  532. var token = CurrentCancellationTokenSource;
  533. if (token != null)
  534. {
  535. try
  536. {
  537. _logger.LogInformation(Name + ": Cancelling");
  538. token.Cancel();
  539. }
  540. catch (Exception ex)
  541. {
  542. _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
  543. }
  544. }
  545. var task = _currentTask;
  546. if (task != null)
  547. {
  548. try
  549. {
  550. _logger.LogInformation(Name + ": Waiting on Task");
  551. var exited = task.Wait(2000);
  552. if (exited)
  553. {
  554. _logger.LogInformation(Name + ": Task exited");
  555. }
  556. else
  557. {
  558. _logger.LogInformation(Name + ": Timed out waiting for task to stop");
  559. }
  560. }
  561. catch (Exception ex)
  562. {
  563. _logger.LogError(ex, "Error calling Task.WaitAll();");
  564. }
  565. }
  566. if (token != null)
  567. {
  568. try
  569. {
  570. _logger.LogDebug(Name + ": Disposing CancellationToken");
  571. token.Dispose();
  572. }
  573. catch (Exception ex)
  574. {
  575. _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
  576. }
  577. }
  578. if (wassRunning)
  579. {
  580. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  581. }
  582. }
  583. }
  584. /// <summary>
  585. /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
  586. /// </summary>
  587. /// <param name="info">The info.</param>
  588. /// <returns>BaseTaskTrigger.</returns>
  589. /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
  590. private ITaskTrigger GetTrigger(TaskTriggerInfo info)
  591. {
  592. var options = new TaskOptions
  593. {
  594. MaxRuntimeTicks = info.MaxRuntimeTicks
  595. };
  596. if (info.Type.Equals(nameof(DailyTrigger), StringComparison.OrdinalIgnoreCase))
  597. {
  598. if (!info.TimeOfDayTicks.HasValue)
  599. {
  600. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  601. }
  602. return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
  603. }
  604. if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
  605. {
  606. if (!info.TimeOfDayTicks.HasValue)
  607. {
  608. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  609. }
  610. if (!info.DayOfWeek.HasValue)
  611. {
  612. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  613. }
  614. return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
  615. }
  616. if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
  617. {
  618. if (!info.IntervalTicks.HasValue)
  619. {
  620. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  621. }
  622. return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
  623. }
  624. if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
  625. {
  626. return new StartupTrigger(options);
  627. }
  628. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  629. }
  630. /// <summary>
  631. /// Disposes each trigger.
  632. /// </summary>
  633. private void DisposeTriggers()
  634. {
  635. foreach (var triggerInfo in InternalTriggers)
  636. {
  637. var trigger = triggerInfo.Item2;
  638. trigger.Triggered -= OnTriggerTriggered;
  639. trigger.Stop();
  640. }
  641. }
  642. }
  643. }