ScheduledTaskWorker.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Data.Events;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Common.Json;
  14. using MediaBrowser.Common.Progress;
  15. using MediaBrowser.Model.Tasks;
  16. using Microsoft.Extensions.Logging;
  17. namespace Emby.Server.Implementations.ScheduledTasks
  18. {
  19. /// <summary>
  20. /// Class ScheduledTaskWorker.
  21. /// </summary>
  22. public class ScheduledTaskWorker : IScheduledTaskWorker
  23. {
  24. /// <summary>
  25. /// Gets or sets the application paths.
  26. /// </summary>
  27. /// <value>The application paths.</value>
  28. private readonly IApplicationPaths _applicationPaths;
  29. /// <summary>
  30. /// Gets or sets the logger.
  31. /// </summary>
  32. /// <value>The logger.</value>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// Gets or sets the task manager.
  36. /// </summary>
  37. /// <value>The task manager.</value>
  38. private readonly ITaskManager _taskManager;
  39. /// <summary>
  40. /// The _last execution result sync lock.
  41. /// </summary>
  42. private readonly object _lastExecutionResultSyncLock = new object();
  43. private bool _readFromFile = false;
  44. /// <summary>
  45. /// The _last execution result.
  46. /// </summary>
  47. private TaskResult _lastExecutionResult;
  48. private Task _currentTask;
  49. /// <summary>
  50. /// The _triggers.
  51. /// </summary>
  52. private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
  53. /// <summary>
  54. /// The _id.
  55. /// </summary>
  56. private string _id;
  57. /// <summary>
  58. /// The options for the json Serializer.
  59. /// </summary>
  60. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  61. /// <summary>
  62. /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
  63. /// </summary>
  64. /// <param name="scheduledTask">The scheduled task.</param>
  65. /// <param name="applicationPaths">The application paths.</param>
  66. /// <param name="taskManager">The task manager.</param>
  67. /// <param name="logger">The logger.</param>
  68. /// <exception cref="ArgumentNullException">
  69. /// scheduledTask
  70. /// or
  71. /// applicationPaths
  72. /// or
  73. /// taskManager
  74. /// or
  75. /// jsonSerializer
  76. /// or
  77. /// logger.
  78. /// </exception>
  79. public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
  80. {
  81. if (scheduledTask == null)
  82. {
  83. throw new ArgumentNullException(nameof(scheduledTask));
  84. }
  85. if (applicationPaths == null)
  86. {
  87. throw new ArgumentNullException(nameof(applicationPaths));
  88. }
  89. if (taskManager == null)
  90. {
  91. throw new ArgumentNullException(nameof(taskManager));
  92. }
  93. if (logger == null)
  94. {
  95. throw new ArgumentNullException(nameof(logger));
  96. }
  97. ScheduledTask = scheduledTask;
  98. _applicationPaths = applicationPaths;
  99. _taskManager = taskManager;
  100. _logger = logger;
  101. InitTriggerEvents();
  102. }
  103. public event EventHandler<GenericEventArgs<double>> TaskProgress;
  104. /// <summary>
  105. /// Gets the scheduled task.
  106. /// </summary>
  107. /// <value>The scheduled task.</value>
  108. public IScheduledTask ScheduledTask { get; private set; }
  109. /// <summary>
  110. /// Gets the last execution result.
  111. /// </summary>
  112. /// <value>The last execution result.</value>
  113. public TaskResult LastExecutionResult
  114. {
  115. get
  116. {
  117. var path = GetHistoryFilePath();
  118. lock (_lastExecutionResultSyncLock)
  119. {
  120. if (_lastExecutionResult == null && !_readFromFile)
  121. {
  122. if (File.Exists(path))
  123. {
  124. var bytes = File.ReadAllBytes(path);
  125. if (bytes.Length > 0)
  126. {
  127. try
  128. {
  129. _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
  130. }
  131. catch (JsonException ex)
  132. {
  133. _logger.LogError(ex, "Error deserializing {File}", path);
  134. }
  135. }
  136. else
  137. {
  138. _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
  139. }
  140. }
  141. _readFromFile = true;
  142. }
  143. }
  144. return _lastExecutionResult;
  145. }
  146. private set
  147. {
  148. _lastExecutionResult = value;
  149. var path = GetHistoryFilePath();
  150. Directory.CreateDirectory(Path.GetDirectoryName(path));
  151. lock (_lastExecutionResultSyncLock)
  152. {
  153. using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  154. JsonSerializer.SerializeAsync(createStream, 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. JsonSerializer.SerializeAsync(createStream, triggers, _jsonOptions);
  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. /// <param name="ex">The exception.</param>
  495. private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
  496. {
  497. var elapsedTime = endTime - startTime;
  498. _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
  499. var result = new TaskResult
  500. {
  501. StartTimeUtc = startTime,
  502. EndTimeUtc = endTime,
  503. Status = status,
  504. Name = Name,
  505. Id = Id
  506. };
  507. result.Key = ScheduledTask.Key;
  508. if (ex != null)
  509. {
  510. result.ErrorMessage = ex.Message;
  511. result.LongErrorMessage = ex.StackTrace;
  512. }
  513. LastExecutionResult = result;
  514. ((TaskManager)_taskManager).OnTaskCompleted(this, result);
  515. }
  516. /// <summary>
  517. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  518. /// </summary>
  519. public void Dispose()
  520. {
  521. Dispose(true);
  522. GC.SuppressFinalize(this);
  523. }
  524. /// <summary>
  525. /// Releases unmanaged and - optionally - managed resources.
  526. /// </summary>
  527. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  528. protected virtual void Dispose(bool dispose)
  529. {
  530. if (dispose)
  531. {
  532. DisposeTriggers();
  533. var wassRunning = State == TaskState.Running;
  534. var startTime = CurrentExecutionStartTime;
  535. var token = CurrentCancellationTokenSource;
  536. if (token != null)
  537. {
  538. try
  539. {
  540. _logger.LogInformation(Name + ": Cancelling");
  541. token.Cancel();
  542. }
  543. catch (Exception ex)
  544. {
  545. _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
  546. }
  547. }
  548. var task = _currentTask;
  549. if (task != null)
  550. {
  551. try
  552. {
  553. _logger.LogInformation(Name + ": Waiting on Task");
  554. var exited = task.Wait(2000);
  555. if (exited)
  556. {
  557. _logger.LogInformation(Name + ": Task exited");
  558. }
  559. else
  560. {
  561. _logger.LogInformation(Name + ": Timed out waiting for task to stop");
  562. }
  563. }
  564. catch (Exception ex)
  565. {
  566. _logger.LogError(ex, "Error calling Task.WaitAll();");
  567. }
  568. }
  569. if (token != null)
  570. {
  571. try
  572. {
  573. _logger.LogDebug(Name + ": Disposing CancellationToken");
  574. token.Dispose();
  575. }
  576. catch (Exception ex)
  577. {
  578. _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
  579. }
  580. }
  581. if (wassRunning)
  582. {
  583. OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
  584. }
  585. }
  586. }
  587. /// <summary>
  588. /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
  589. /// </summary>
  590. /// <param name="info">The info.</param>
  591. /// <returns>BaseTaskTrigger.</returns>
  592. /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
  593. private ITaskTrigger GetTrigger(TaskTriggerInfo info)
  594. {
  595. var options = new TaskOptions
  596. {
  597. MaxRuntimeTicks = info.MaxRuntimeTicks
  598. };
  599. if (info.Type.Equals(nameof(DailyTrigger), StringComparison.OrdinalIgnoreCase))
  600. {
  601. if (!info.TimeOfDayTicks.HasValue)
  602. {
  603. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  604. }
  605. return new DailyTrigger
  606. {
  607. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  608. TaskOptions = options
  609. };
  610. }
  611. if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
  612. {
  613. if (!info.TimeOfDayTicks.HasValue)
  614. {
  615. throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
  616. }
  617. if (!info.DayOfWeek.HasValue)
  618. {
  619. throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
  620. }
  621. return new WeeklyTrigger
  622. {
  623. TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
  624. DayOfWeek = info.DayOfWeek.Value,
  625. TaskOptions = options
  626. };
  627. }
  628. if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
  629. {
  630. if (!info.IntervalTicks.HasValue)
  631. {
  632. throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
  633. }
  634. return new IntervalTrigger
  635. {
  636. Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
  637. TaskOptions = options
  638. };
  639. }
  640. if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
  641. {
  642. return new StartupTrigger();
  643. }
  644. throw new ArgumentException("Unrecognized trigger type: " + info.Type);
  645. }
  646. /// <summary>
  647. /// Disposes each trigger.
  648. /// </summary>
  649. private void DisposeTriggers()
  650. {
  651. foreach (var triggerInfo in InternalTriggers)
  652. {
  653. var trigger = triggerInfo.Item2;
  654. trigger.Triggered -= OnTriggerTriggered;
  655. trigger.Stop();
  656. }
  657. }
  658. }
  659. }