2
0

IntervalTrigger.cs 2.7 KB

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