ScheduledTaskWorker.cs 25 KB

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