IntervalTrigger.cs 2.9 KB

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