IntervalTrigger.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. triggerDate = DateTime.UtcNow;
  43. if (isApplicationStartup)
  44. {
  45. triggerDate = triggerDate.AddMinutes(1);
  46. }
  47. }
  48. Timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.UtcNow, TimeSpan.FromMilliseconds(-1));
  49. }
  50. /// <summary>
  51. /// Stops waiting for the trigger action
  52. /// </summary>
  53. public void Stop()
  54. {
  55. DisposeTimer();
  56. }
  57. /// <summary>
  58. /// Disposes the timer.
  59. /// </summary>
  60. private void DisposeTimer()
  61. {
  62. if (Timer != null)
  63. {
  64. Timer.Dispose();
  65. }
  66. }
  67. /// <summary>
  68. /// Occurs when [triggered].
  69. /// </summary>
  70. public event EventHandler<GenericEventArgs<TaskExecutionOptions>> Triggered;
  71. /// <summary>
  72. /// Called when [triggered].
  73. /// </summary>
  74. private void OnTriggered()
  75. {
  76. if (Triggered != null)
  77. {
  78. Triggered(this, new GenericEventArgs<TaskExecutionOptions>(TaskOptions));
  79. }
  80. }
  81. }
  82. }