ScheduledTaskWorker.cs 25 KB

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