ScheduledTaskWorker.cs 25 KB

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