ScheduledTaskWorker.cs 25 KB

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