ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Common.Progress;
  11. using MediaBrowser.Model.Events;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Serialization;
  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. public event EventHandler<GenericEventArgs<double>> TaskProgress;
  24. /// <summary>
  25. /// Gets the scheduled task.
  26. /// </summary>
  27. /// <value>The scheduled task.</value>
  28. public IScheduledTask ScheduledTask { get; private set; }
  29. /// <summary>
  30. /// Gets or sets the json serializer.
  31. /// </summary>
  32. /// <value>The json serializer.</value>
  33. private IJsonSerializer JsonSerializer { get; set; }
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. private IApplicationPaths ApplicationPaths { get; set; }
  39. /// <summary>
  40. /// Gets the logger.
  41. /// </summary>
  42. /// <value>The logger.</value>
  43. private ILogger Logger { get; set; }
  44. /// <summary>
  45. /// Gets the task manager.
  46. /// </summary>
  47. /// <value>The task manager.</value>
  48. private ITaskManager TaskManager { get; set; }
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
  51. /// </summary>
  52. /// <param name="scheduledTask">The scheduled task.</param>
  53. /// <param name="applicationPaths">The application paths.</param>
  54. /// <param name="taskManager">The task manager.</param>
  55. /// <param name="jsonSerializer">The json serializer.</param>
  56. /// <param name="logger">The logger.</param>
  57. /// <exception cref="ArgumentNullException">
  58. /// scheduledTask
  59. /// or
  60. /// applicationPaths
  61. /// or
  62. /// taskManager
  63. /// or
  64. /// jsonSerializer
  65. /// or
  66. /// logger
  67. /// </exception>
  68. public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger)
  69. {
  70. if (scheduledTask == null)
  71. {
  72. throw new ArgumentNullException(nameof(scheduledTask));
  73. }
  74. if (applicationPaths == null)
  75. {
  76. throw new ArgumentNullException(nameof(applicationPaths));
  77. }
  78. if (taskManager == null)
  79. {
  80. throw new ArgumentNullException(nameof(taskManager));
  81. }
  82. if (jsonSerializer == null)
  83. {
  84. throw new ArgumentNullException(nameof(jsonSerializer));
  85. }
  86. if (logger == null)
  87. {
  88. throw new ArgumentNullException(nameof(logger));
  89. }
  90. ScheduledTask = scheduledTask;
  91. ApplicationPaths = applicationPaths;
  92. TaskManager = taskManager;
  93. JsonSerializer = jsonSerializer;
  94. Logger = logger;
  95. InitTriggerEvents();
  96. }
  97. private bool _readFromFile = false;
  98. /// <summary>
  99. /// The _last execution result
  100. /// </summary>
  101. private TaskResult _lastExecutionResult;
  102. /// <summary>
  103. /// The _last execution result sync lock
  104. /// </summary>
  105. private readonly object _lastExecutionResultSyncLock = new object();
  106. /// <summary>
  107. /// Gets the last execution result.
  108. /// </summary>
  109. /// <value>The last execution result.</value>
  110. public TaskResult LastExecutionResult
  111. {
  112. get
  113. {
  114. var path = GetHistoryFilePath();
  115. lock (_lastExecutionResultSyncLock)
  116. {
  117. if (_lastExecutionResult == null && !_readFromFile)
  118. {
  119. if (File.Exists(path))
  120. {
  121. try
  122. {
  123. _lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path);
  124. }
  125. catch (Exception ex)
  126. {
  127. Logger.LogError(ex, "Error deserializing {File}", 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. JsonSerializer.SerializeToFile(value, path);
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// Gets the name.
  148. /// </summary>
  149. /// <value>The name.</value>
  150. public string Name => ScheduledTask.Name;
  151. /// <summary>
  152. /// Gets the description.
  153. /// </summary>
  154. /// <value>The description.</value>
  155. public string Description => ScheduledTask.Description;
  156. /// <summary>
  157. /// Gets the category.
  158. /// </summary>
  159. /// <value>The category.</value>
  160. public string Category => ScheduledTask.Category;
  161. /// <summary>
  162. /// Gets the current cancellation token
  163. /// </summary>
  164. /// <value>The current cancellation token source.</value>
  165. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  166. /// <summary>
  167. /// Gets or sets the current execution start time.
  168. /// </summary>
  169. /// <value>The current execution start time.</value>
  170. private DateTime CurrentExecutionStartTime { get; set; }
  171. /// <summary>
  172. /// Gets the state.
  173. /// </summary>
  174. /// <value>The state.</value>
  175. public TaskState State
  176. {
  177. get
  178. {
  179. if (CurrentCancellationTokenSource != null)
  180. {
  181. return CurrentCancellationTokenSource.IsCancellationRequested
  182. ? TaskState.Cancelling
  183. : TaskState.Running;
  184. }
  185. return TaskState.Idle;
  186. }
  187. }
  188. /// <summary>
  189. /// Gets the current progress.
  190. /// </summary>
  191. /// <value>The current progress.</value>
  192. public double? CurrentProgress { get; private set; }
  193. /// <summary>
  194. /// The _triggers.
  195. /// </summary>
  196. private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
  197. /// <summary>
  198. /// Gets the triggers that define when the task will run.
  199. /// </summary>
  200. /// <value>The triggers.</value>
  201. private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
  202. {
  203. get => _triggers;
  204. set
  205. {
  206. if (value == null)
  207. {
  208. throw new ArgumentNullException(nameof(value));
  209. }
  210. // Cleanup current triggers
  211. if (_triggers != null)
  212. {
  213. DisposeTriggers();
  214. }
  215. _triggers = value.ToArray();
  216. ReloadTriggerEvents(false);
  217. }
  218. }
  219. /// <summary>
  220. /// Gets the triggers that define when the task will run.
  221. /// </summary>
  222. /// <value>The triggers.</value>
  223. /// <exception cref="ArgumentNullException">value</exception>
  224. public TaskTriggerInfo[] Triggers
  225. {
  226. get
  227. {
  228. var triggers = InternalTriggers;
  229. return triggers.Select(i => i.Item1).ToArray();
  230. }
  231. set
  232. {
  233. if (value == null)
  234. {
  235. throw new ArgumentNullException(nameof(value));
  236. }
  237. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  238. var triggerList = value.Where(i => i != null).ToArray();
  239. SaveTriggers(triggerList);
  240. InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  241. }
  242. }
  243. /// <summary>
  244. /// The _id
  245. /// </summary>
  246. private string _id;
  247. /// <summary>
  248. /// Gets the unique id.
  249. /// </summary>
  250. /// <value>The unique id.</value>
  251. public string Id
  252. {
  253. get
  254. {
  255. if (_id == null)
  256. {
  257. _id = ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  258. }
  259. return _id;
  260. }
  261. }
  262. private void InitTriggerEvents()
  263. {
  264. _triggers = LoadTriggers();
  265. ReloadTriggerEvents(true);
  266. }
  267. public void ReloadTriggerEvents()
  268. {
  269. ReloadTriggerEvents(false);
  270. }
  271. /// <summary>
  272. /// Reloads the trigger events.
  273. /// </summary>
  274. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  275. private void ReloadTriggerEvents(bool isApplicationStartup)
  276. {
  277. foreach (var triggerInfo in InternalTriggers)
  278. {
  279. var trigger = triggerInfo.Item2;
  280. trigger.Stop();
  281. trigger.Triggered -= trigger_Triggered;
  282. trigger.Triggered += trigger_Triggered;
  283. trigger.Start(LastExecutionResult, Logger, Name, isApplicationStartup);
  284. }
  285. }
  286. /// <summary>
  287. /// Handles the Triggered event of the trigger control.
  288. /// </summary>
  289. /// <param name="sender">The source of the event.</param>
  290. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  291. async void trigger_Triggered(object sender, EventArgs e)
  292. {
  293. var trigger = (ITaskTrigger)sender;
  294. var configurableTask = ScheduledTask as IConfigurableScheduledTask;
  295. if (configurableTask != null && !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. private Task _currentTask;
  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 += progress_ProgressChanged;
  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.Execute(CurrentCancellationTokenSource.Token, progress).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 -= progress_ProgressChanged;
  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. void progress_ProgressChanged(object sender, double e)
  374. {
  375. e = Math.Min(e, 100);
  376. CurrentProgress = e;
  377. TaskProgress?.Invoke(this, new GenericEventArgs<double>
  378. {
  379. Argument = e
  380. });
  381. }
  382. /// <summary>
  383. /// Stops the task if it is currently executing
  384. /// </summary>
  385. /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  386. public void Cancel()
  387. {
  388. if (State != TaskState.Running)
  389. {
  390. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  391. }
  392. CancelIfRunning();
  393. }
  394. /// <summary>
  395. /// Cancels if running.
  396. /// </summary>
  397. public void CancelIfRunning()
  398. {
  399. if (State == TaskState.Running)
  400. {
  401. Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
  402. CurrentCancellationTokenSource.Cancel();
  403. }
  404. }
  405. /// <summary>
  406. /// Gets the scheduled tasks configuration directory.
  407. /// </summary>
  408. /// <returns>System.String.</returns>
  409. private string GetScheduledTasksConfigurationDirectory()
  410. {
  411. return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  412. }
  413. /// <summary>
  414. /// Gets the scheduled tasks data directory.
  415. /// </summary>
  416. /// <returns>System.String.</returns>
  417. private string GetScheduledTasksDataDirectory()
  418. {
  419. return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
  420. }
  421. /// <summary>
  422. /// Gets the history file path.
  423. /// </summary>
  424. /// <value>The history file path.</value>
  425. private string GetHistoryFilePath()
  426. {
  427. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  428. }
  429. /// <summary>
  430. /// Gets the configuration file path.
  431. /// </summary>
  432. /// <returns>System.String.</returns>
  433. private string GetConfigurationFilePath()
  434. {
  435. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  436. }
  437. /// <summary>
  438. /// Loads the triggers.
  439. /// </summary>
  440. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  441. private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
  442. {
  443. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  444. var settings = LoadTriggerSettings().Where(i => i != null).ToArray();
  445. return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  446. }
  447. private TaskTriggerInfo[] LoadTriggerSettings()
  448. {
  449. string path = GetConfigurationFilePath();
  450. TaskTriggerInfo[] list = null;
  451. if (File.Exists(path))
  452. {
  453. list = JsonSerializer.DeserializeFromFile<TaskTriggerInfo[]>(path);
  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. JsonSerializer.SerializeToFile(triggers, path);
  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. }
  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.WaitAll(new[] { task }, 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="ArgumentNullException"></exception>
  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(typeof(DailyTrigger).Name, 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
  604. {
  605. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  606. TaskOptions = options
  607. };
  608. }
  609. if (info.Type.Equals(typeof(WeeklyTrigger).Name, StringComparison.OrdinalIgnoreCase))
  610. {
  611. if (!info.TimeOfDayTicks.HasValue)
  612. {
  613. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  614. }
  615. if (!info.DayOfWeek.HasValue)
  616. {
  617. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  618. }
  619. return new WeeklyTrigger
  620. {
  621. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  622. DayOfWeek = info.DayOfWeek.Value,
  623. TaskOptions = options
  624. };
  625. }
  626. if (info.Type.Equals(typeof(IntervalTrigger).Name, StringComparison.OrdinalIgnoreCase))
  627. {
  628. if (!info.IntervalTicks.HasValue)
  629. {
  630. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  631. }
  632. return new IntervalTrigger
  633. {
  634. Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
  635. TaskOptions = options
  636. };
  637. }
  638. if (info.Type.Equals(typeof(StartupTrigger).Name, StringComparison.OrdinalIgnoreCase))
  639. {
  640. return new StartupTrigger();
  641. }
  642. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  643. }
  644. /// <summary>
  645. /// Disposes each trigger
  646. /// </summary>
  647. private void DisposeTriggers()
  648. {
  649. foreach (var triggerInfo in InternalTriggers)
  650. {
  651. var trigger = triggerInfo.Item2;
  652. trigger.Triggered -= trigger_Triggered;
  653. trigger.Stop();
  654. }
  655. }
  656. }
  657. }