2
0

ScheduledTaskWorker.cs 25 KB

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