IntervalTrigger.cs 2.8 KB

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