ScheduledTaskWorker.cs 25 KB

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