ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Extensions;
  9. using MediaBrowser.Common.Progress;
  10. using MediaBrowser.Model.Events;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Serialization;
  13. using MediaBrowser.Model.System;
  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 or sets 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. private readonly IFileSystem _fileSystem;
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
  52. /// </summary>
  53. /// <param name="scheduledTask">The scheduled task.</param>
  54. /// <param name="applicationPaths">The application paths.</param>
  55. /// <param name="taskManager">The task manager.</param>
  56. /// <param name="jsonSerializer">The json serializer.</param>
  57. /// <param name="logger">The logger.</param>
  58. /// <exception cref="ArgumentNullException">
  59. /// scheduledTask
  60. /// or
  61. /// applicationPaths
  62. /// or
  63. /// taskManager
  64. /// or
  65. /// jsonSerializer
  66. /// or
  67. /// logger
  68. /// </exception>
  69. public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem)
  70. {
  71. if (scheduledTask == null)
  72. {
  73. throw new ArgumentNullException(nameof(scheduledTask));
  74. }
  75. if (applicationPaths == null)
  76. {
  77. throw new ArgumentNullException(nameof(applicationPaths));
  78. }
  79. if (taskManager == null)
  80. {
  81. throw new ArgumentNullException(nameof(taskManager));
  82. }
  83. if (jsonSerializer == null)
  84. {
  85. throw new ArgumentNullException(nameof(jsonSerializer));
  86. }
  87. if (logger == null)
  88. {
  89. throw new ArgumentNullException(nameof(logger));
  90. }
  91. ScheduledTask = scheduledTask;
  92. ApplicationPaths = applicationPaths;
  93. TaskManager = taskManager;
  94. JsonSerializer = jsonSerializer;
  95. Logger = logger;
  96. _fileSystem = fileSystem;
  97. InitTriggerEvents();
  98. }
  99. private bool _readFromFile = false;
  100. /// <summary>
  101. /// The _last execution result
  102. /// </summary>
  103. private TaskResult _lastExecutionResult;
  104. /// <summary>
  105. /// The _last execution result sync lock
  106. /// </summary>
  107. private readonly object _lastExecutionResultSyncLock = new object();
  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. _lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path);
  126. }
  127. catch (Exception ex)
  128. {
  129. Logger.LogError(ex, "Error deserializing {File}", path);
  130. }
  131. }
  132. _readFromFile = true;
  133. }
  134. }
  135. return _lastExecutionResult;
  136. }
  137. private set
  138. {
  139. _lastExecutionResult = value;
  140. var path = GetHistoryFilePath();
  141. Directory.CreateDirectory(Path.GetDirectoryName(path));
  142. lock (_lastExecutionResultSyncLock)
  143. {
  144. JsonSerializer.SerializeToFile(value, path);
  145. }
  146. }
  147. }
  148. /// <summary>
  149. /// Gets the name.
  150. /// </summary>
  151. /// <value>The name.</value>
  152. public string Name => ScheduledTask.Name;
  153. /// <summary>
  154. /// Gets the description.
  155. /// </summary>
  156. /// <value>The description.</value>
  157. public string Description => ScheduledTask.Description;
  158. /// <summary>
  159. /// Gets the category.
  160. /// </summary>
  161. /// <value>The category.</value>
  162. public string Category => ScheduledTask.Category;
  163. /// <summary>
  164. /// Gets the current cancellation token
  165. /// </summary>
  166. /// <value>The current cancellation token source.</value>
  167. private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
  168. /// <summary>
  169. /// Gets or sets the current execution start time.
  170. /// </summary>
  171. /// <value>The current execution start time.</value>
  172. private DateTime CurrentExecutionStartTime { get; set; }
  173. /// <summary>
  174. /// Gets the state.
  175. /// </summary>
  176. /// <value>The state.</value>
  177. public TaskState State
  178. {
  179. get
  180. {
  181. if (CurrentCancellationTokenSource != null)
  182. {
  183. return CurrentCancellationTokenSource.IsCancellationRequested
  184. ? TaskState.Cancelling
  185. : TaskState.Running;
  186. }
  187. return TaskState.Idle;
  188. }
  189. }
  190. /// <summary>
  191. /// Gets the current progress.
  192. /// </summary>
  193. /// <value>The current progress.</value>
  194. public double? CurrentProgress { get; private set; }
  195. /// <summary>
  196. /// The _triggers
  197. /// </summary>
  198. private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
  199. /// <summary>
  200. /// Gets the triggers that define when the task will run
  201. /// </summary>
  202. /// <value>The triggers.</value>
  203. private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
  204. {
  205. get => _triggers;
  206. set
  207. {
  208. if (value == null)
  209. {
  210. throw new ArgumentNullException(nameof(value));
  211. }
  212. // Cleanup current triggers
  213. if (_triggers != null)
  214. {
  215. DisposeTriggers();
  216. }
  217. _triggers = value.ToArray();
  218. ReloadTriggerEvents(false);
  219. }
  220. }
  221. /// <summary>
  222. /// Gets the triggers that define when the task will run
  223. /// </summary>
  224. /// <value>The triggers.</value>
  225. /// <exception cref="ArgumentNullException">value</exception>
  226. public TaskTriggerInfo[] Triggers
  227. {
  228. get
  229. {
  230. var triggers = InternalTriggers;
  231. return triggers.Select(i => i.Item1).ToArray();
  232. }
  233. set
  234. {
  235. if (value == null)
  236. {
  237. throw new ArgumentNullException(nameof(value));
  238. }
  239. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  240. var triggerList = value.Where(i => i != null).ToArray();
  241. SaveTriggers(triggerList);
  242. InternalTriggers = triggerList.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  243. }
  244. }
  245. /// <summary>
  246. /// The _id
  247. /// </summary>
  248. private string _id;
  249. /// <summary>
  250. /// Gets the unique id.
  251. /// </summary>
  252. /// <value>The unique id.</value>
  253. public string Id
  254. {
  255. get
  256. {
  257. if (_id == null)
  258. {
  259. _id = ScheduledTask.GetType().FullName.GetMD5().ToString("N");
  260. }
  261. return _id;
  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 -= trigger_Triggered;
  284. trigger.Triggered += trigger_Triggered;
  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. async void trigger_Triggered(object sender, EventArgs e)
  294. {
  295. var trigger = (ITaskTrigger)sender;
  296. var configurableTask = ScheduledTask as IConfigurableScheduledTask;
  297. if (configurableTask != null && !configurableTask.IsEnabled)
  298. {
  299. return;
  300. }
  301. Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name);
  302. trigger.Stop();
  303. TaskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
  304. await Task.Delay(1000).ConfigureAwait(false);
  305. trigger.Start(LastExecutionResult, Logger, Name, false);
  306. }
  307. private Task _currentTask;
  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 += progress_ProgressChanged;
  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 -= progress_ProgressChanged;
  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. void progress_ProgressChanged(object sender, double e)
  376. {
  377. e = Math.Min(e, 100);
  378. CurrentProgress = e;
  379. TaskProgress?.Invoke(this, new GenericEventArgs<double>
  380. {
  381. Argument = e
  382. });
  383. }
  384. /// <summary>
  385. /// Stops the task if it is currently executing
  386. /// </summary>
  387. /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  388. public void Cancel()
  389. {
  390. if (State != TaskState.Running)
  391. {
  392. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  393. }
  394. CancelIfRunning();
  395. }
  396. /// <summary>
  397. /// Cancels if running.
  398. /// </summary>
  399. public void CancelIfRunning()
  400. {
  401. if (State == TaskState.Running)
  402. {
  403. Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
  404. CurrentCancellationTokenSource.Cancel();
  405. }
  406. }
  407. /// <summary>
  408. /// Gets the scheduled tasks configuration directory.
  409. /// </summary>
  410. /// <returns>System.String.</returns>
  411. private string GetScheduledTasksConfigurationDirectory()
  412. {
  413. return Path.Combine(ApplicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  414. }
  415. /// <summary>
  416. /// Gets the scheduled tasks data directory.
  417. /// </summary>
  418. /// <returns>System.String.</returns>
  419. private string GetScheduledTasksDataDirectory()
  420. {
  421. return Path.Combine(ApplicationPaths.DataPath, "ScheduledTasks");
  422. }
  423. /// <summary>
  424. /// Gets the history file path.
  425. /// </summary>
  426. /// <value>The history file path.</value>
  427. private string GetHistoryFilePath()
  428. {
  429. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  430. }
  431. /// <summary>
  432. /// Gets the configuration file path.
  433. /// </summary>
  434. /// <returns>System.String.</returns>
  435. private string GetConfigurationFilePath()
  436. {
  437. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  438. }
  439. /// <summary>
  440. /// Loads the triggers.
  441. /// </summary>
  442. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  443. private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
  444. {
  445. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  446. var settings = LoadTriggerSettings().Where(i => i != null).ToArray();
  447. return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  448. }
  449. private TaskTriggerInfo[] LoadTriggerSettings()
  450. {
  451. string path = GetConfigurationFilePath();
  452. TaskTriggerInfo[] list = null;
  453. if (File.Exists(path))
  454. {
  455. list = JsonSerializer.DeserializeFromFile<TaskTriggerInfo[]>(path);
  456. }
  457. // Return defaults if file doesn't exist.
  458. return list ?? GetDefaultTriggers();
  459. }
  460. private TaskTriggerInfo[] GetDefaultTriggers()
  461. {
  462. try
  463. {
  464. return ScheduledTask.GetDefaultTriggers().ToArray();
  465. }
  466. catch
  467. {
  468. return new TaskTriggerInfo[]
  469. {
  470. new TaskTriggerInfo
  471. {
  472. IntervalTicks = TimeSpan.FromDays(1).Ticks,
  473. Type = TaskTriggerInfo.TriggerInterval
  474. }
  475. };
  476. }
  477. }
  478. /// <summary>
  479. /// Saves the triggers.
  480. /// </summary>
  481. /// <param name="triggers">The triggers.</param>
  482. private void SaveTriggers(TaskTriggerInfo[] triggers)
  483. {
  484. var path = GetConfigurationFilePath();
  485. Directory.CreateDirectory(Path.GetDirectoryName(path));
  486. JsonSerializer.SerializeToFile(triggers, path);
  487. }
  488. /// <summary>
  489. /// Called when [task completed].
  490. /// </summary>
  491. /// <param name="startTime">The start time.</param>
  492. /// <param name="endTime">The end time.</param>
  493. /// <param name="status">The status.</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. }
  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");
  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");
  552. var exited = Task.WaitAll(new[] { task }, 2000);
  553. if (exited)
  554. {
  555. Logger.LogInformation(Name + ": Task exited");
  556. }
  557. else
  558. {
  559. Logger.LogInformation(Name + ": Timed out waiting for task to stop");
  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");
  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="ArgumentNullException"></exception>
  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(typeof(DailyTrigger).Name, 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(typeof(WeeklyTrigger).Name, 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(typeof(IntervalTrigger).Name, 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(typeof(StartupTrigger).Name, 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 -= trigger_Triggered;
  654. trigger.Stop();
  655. }
  656. }
  657. }
  658. }