IntervalTrigger.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Threading;
  3. using MediaBrowser.Model.Events;
  4. namespace MediaBrowser.Common.ScheduledTasks
  5. {
  6. /// <summary>
  7. /// Represents a task trigger that runs repeatedly on an interval
  8. /// </summary>
  9. public class IntervalTrigger : ITaskTrigger
  10. {
  11. /// <summary>
  12. /// Gets or sets the interval.
  13. /// </summary>
  14. /// <value>The interval.</value>
  15. public TimeSpan Interval { get; set; }
  16. /// <summary>
  17. /// Gets or sets the timer.
  18. /// </summary>
  19. /// <value>The timer.</value>
  20. private Timer Timer { get; set; }
  21. /// <summary>
  22. /// Gets the execution properties of this task.
  23. /// </summary>
  24. /// <value>
  25. /// The execution properties of this task.
  26. /// </value>
  27. public TaskExecutionOptions TaskOptions { get; set; }
  28. /// <summary>
  29. /// Stars waiting for the trigger action
  30. /// </summary>
  31. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  32. public void Start(bool isApplicationStartup)
  33. {
  34. DisposeTimer();
  35. Timer = new Timer(state => OnTriggered(), null, Interval, TimeSpan.FromMilliseconds(-1));
  36. }
  37. /// <summary>
  38. /// Stops waiting for the trigger action
  39. /// </summary>
  40. public void Stop()
  41. {
  42. DisposeTimer();
  43. }
  44. /// <summary>
  45. /// Disposes the timer.
  46. /// </summary>
  47. private void DisposeTimer()
  48. {
  49. if (Timer != null)
  50. {
  51. Timer.Dispose();
  52. }
  53. }
  54. /// <summary>
  55. /// Occurs when [triggered].
  56. /// </summary>
  57. public event EventHandler<GenericEventArgs<TaskExecutionOptions>> Triggered;
  58. /// <summary>
  59. /// Called when [triggered].
  60. /// </summary>
  61. private void OnTriggered()
  62. {
  63. if (Triggered != null)
  64. {
  65. Triggered(this, new GenericEventArgs<TaskExecutionOptions>(TaskOptions));
  66. }
  67. }
  68. }
  69. }