ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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. return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  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 -= OnTriggerTriggered;
  282. trigger.Triggered += OnTriggerTriggered;
  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. private async void OnTriggerTriggered(object sender, EventArgs e)
  292. {
  293. var trigger = (ITaskTrigger)sender;
  294. if (ScheduledTask is IConfigurableScheduledTask configurableTask && !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. /// <summary>
  305. /// Executes the task.
  306. /// </summary>
  307. /// <param name="options">Task options.</param>
  308. /// <returns>Task.</returns>
  309. /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running</exception>
  310. public async Task Execute(TaskOptions options)
  311. {
  312. var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
  313. _currentTask = task;
  314. try
  315. {
  316. await task.ConfigureAwait(false);
  317. }
  318. finally
  319. {
  320. _currentTask = null;
  321. GC.Collect();
  322. }
  323. }
  324. private async Task ExecuteInternal(TaskOptions options)
  325. {
  326. // Cancel the current execution, if any
  327. if (CurrentCancellationTokenSource != null)
  328. {
  329. throw new InvalidOperationException("Cannot execute a Task that is already running");
  330. }
  331. var progress = new SimpleProgress<double>();
  332. CurrentCancellationTokenSource = new CancellationTokenSource();
  333. _logger.LogInformation("Executing {0}", Name);
  334. ((TaskManager)_taskManager).OnTaskExecuting(this);
  335. progress.ProgressChanged += OnProgressChanged;
  336. TaskCompletionStatus status;
  337. CurrentExecutionStartTime = DateTime.UtcNow;
  338. Exception failureException = null;
  339. try
  340. {
  341. if (options != null && options.MaxRuntimeTicks.HasValue)
  342. {
  343. CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
  344. }
  345. await ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false);
  346. status = TaskCompletionStatus.Completed;
  347. }
  348. catch (OperationCanceledException)
  349. {
  350. status = TaskCompletionStatus.Cancelled;
  351. }
  352. catch (Exception ex)
  353. {
  354. _logger.LogError(ex, "Error");
  355. failureException = ex;
  356. status = TaskCompletionStatus.Failed;
  357. }
  358. var startTime = CurrentExecutionStartTime;
  359. var endTime = DateTime.UtcNow;
  360. progress.ProgressChanged -= OnProgressChanged;
  361. CurrentCancellationTokenSource.Dispose();
  362. CurrentCancellationTokenSource = null;
  363. CurrentProgress = null;
  364. OnTaskCompleted(startTime, endTime, status, failureException);
  365. }
  366. /// <summary>
  367. /// Progress_s the progress changed.
  368. /// </summary>
  369. /// <param name="sender">The sender.</param>
  370. /// <param name="e">The e.</param>
  371. private void OnProgressChanged(object sender, double e)
  372. {
  373. e = Math.Min(e, 100);
  374. CurrentProgress = e;
  375. TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
  376. }
  377. /// <summary>
  378. /// Stops the task if it is currently executing.
  379. /// </summary>
  380. /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
  381. public void Cancel()
  382. {
  383. if (State != TaskState.Running)
  384. {
  385. throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
  386. }
  387. CancelIfRunning();
  388. }
  389. /// <summary>
  390. /// Cancels if running.
  391. /// </summary>
  392. public void CancelIfRunning()
  393. {
  394. if (State == TaskState.Running)
  395. {
  396. _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
  397. CurrentCancellationTokenSource.Cancel();
  398. }
  399. }
  400. /// <summary>
  401. /// Gets the scheduled tasks configuration directory.
  402. /// </summary>
  403. /// <returns>System.String.</returns>
  404. private string GetScheduledTasksConfigurationDirectory()
  405. {
  406. return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
  407. }
  408. /// <summary>
  409. /// Gets the scheduled tasks data directory.
  410. /// </summary>
  411. /// <returns>System.String.</returns>
  412. private string GetScheduledTasksDataDirectory()
  413. {
  414. return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
  415. }
  416. /// <summary>
  417. /// Gets the history file path.
  418. /// </summary>
  419. /// <value>The history file path.</value>
  420. private string GetHistoryFilePath()
  421. {
  422. return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
  423. }
  424. /// <summary>
  425. /// Gets the configuration file path.
  426. /// </summary>
  427. /// <returns>System.String.</returns>
  428. private string GetConfigurationFilePath()
  429. {
  430. return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
  431. }
  432. /// <summary>
  433. /// Loads the triggers.
  434. /// </summary>
  435. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  436. private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
  437. {
  438. // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
  439. var settings = LoadTriggerSettings().Where(i => i != null).ToArray();
  440. return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
  441. }
  442. private TaskTriggerInfo[] LoadTriggerSettings()
  443. {
  444. string path = GetConfigurationFilePath();
  445. TaskTriggerInfo[] list = null;
  446. if (File.Exists(path))
  447. {
  448. var bytes = File.ReadAllBytes(path);
  449. list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
  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. using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  481. using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
  482. JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
  483. }
  484. /// <summary>
  485. /// Called when [task completed].
  486. /// </summary>
  487. /// <param name="startTime">The start time.</param>
  488. /// <param name="endTime">The end time.</param>
  489. /// <param name="status">The status.</param>
  490. /// <param name="ex">The exception.</param>
  491. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  492. {
  493. var elapsedTime = endTime - startTime;
  494. _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  495. var result = new TaskResult
  496. {
  497. StartTimeUtc = startTime,
  498. EndTimeUtc = endTime,
  499. Status = status,
  500. Name = Name,
  501. Id = Id
  502. };
  503. result.Key = ScheduledTask.Key;
  504. if (ex != null)
  505. {
  506. result.ErrorMessage = ex.Message;
  507. result.LongErrorMessage = ex.StackTrace;
  508. }
  509. LastExecutionResult = result;
  510. ((TaskManager)_taskManager).OnTaskCompleted(this, result);
  511. }
  512. /// <summary>
  513. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  514. /// </summary>
  515. public void Dispose()
  516. {
  517. Dispose(true);
  518. GC.SuppressFinalize(this);
  519. }
  520. /// <summary>
  521. /// Releases unmanaged and - optionally - managed resources.
  522. /// </summary>
  523. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  524. protected virtual void Dispose(bool dispose)
  525. {
  526. if (dispose)
  527. {
  528. DisposeTriggers();
  529. var wassRunning = State == TaskState.Running;
  530. var startTime = CurrentExecutionStartTime;
  531. var token = CurrentCancellationTokenSource;
  532. if (token != null)
  533. {
  534. try
  535. {
  536. _logger.LogInformation(Name + ": Cancelling");
  537. token.Cancel();
  538. }
  539. catch (Exception ex)
  540. {
  541. _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
  542. }
  543. }
  544. var task = _currentTask;
  545. if (task != null)
  546. {
  547. try
  548. {
  549. _logger.LogInformation(Name + ": Waiting on Task");
  550. var exited = task.Wait(2000);
  551. if (exited)
  552. {
  553. _logger.LogInformation(Name + ": Task exited");
  554. }
  555. else
  556. {
  557. _logger.LogInformation(Name + ": Timed out waiting for task to stop");
  558. }
  559. }
  560. catch (Exception ex)
  561. {
  562. _logger.LogError(ex, "Error calling Task.WaitAll();");
  563. }
  564. }
  565. if (token != null)
  566. {
  567. try
  568. {
  569. _logger.LogDebug(Name + ": Disposing CancellationToken");
  570. token.Dispose();
  571. }
  572. catch (Exception ex)
  573. {
  574. _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
  575. }
  576. }
  577. if (wassRunning)
  578. {
  579. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  580. }
  581. }
  582. }
  583. /// <summary>
  584. /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
  585. /// </summary>
  586. /// <param name="info">The info.</param>
  587. /// <returns>BaseTaskTrigger.</returns>
  588. /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
  589. private ITaskTrigger GetTrigger(TaskTriggerInfo info)
  590. {
  591. var options = new TaskOptions
  592. {
  593. MaxRuntimeTicks = info.MaxRuntimeTicks
  594. };
  595. if (info.Type.Equals(nameof(DailyTrigger), StringComparison.OrdinalIgnoreCase))
  596. {
  597. if (!info.TimeOfDayTicks.HasValue)
  598. {
  599. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  600. }
  601. return new DailyTrigger
  602. {
  603. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  604. TaskOptions = options
  605. };
  606. }
  607. if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
  608. {
  609. if (!info.TimeOfDayTicks.HasValue)
  610. {
  611. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  612. }
  613. if (!info.DayOfWeek.HasValue)
  614. {
  615. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  616. }
  617. return new WeeklyTrigger
  618. {
  619. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  620. DayOfWeek = info.DayOfWeek.Value,
  621. TaskOptions = options
  622. };
  623. }
  624. if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
  625. {
  626. if (!info.IntervalTicks.HasValue)
  627. {
  628. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  629. }
  630. return new IntervalTrigger
  631. {
  632. Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
  633. TaskOptions = options
  634. };
  635. }
  636. if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
  637. {
  638. return new StartupTrigger();
  639. }
  640. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  641. }
  642. /// <summary>
  643. /// Disposes each trigger.
  644. /// </summary>
  645. private void DisposeTriggers()
  646. {
  647. foreach (var triggerInfo in InternalTriggers)
  648. {
  649. var trigger = triggerInfo.Item2;
  650. trigger.Triggered -= OnTriggerTriggered;
  651. trigger.Stop();
  652. }
  653. }
  654. }
  655. }