DailyTrigger.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Threading;
  3. using MediaBrowser.Model.Tasks;
  4. using Microsoft.Extensions.Logging;
  5. namespace Emby.Server.Implementations.ScheduledTasks
  6. {
  7. /// <summary>
  8. /// Represents a task trigger that fires everyday.
  9. /// </summary>
  10. public sealed class DailyTrigger : ITaskTrigger
  11. {
  12. private readonly TimeSpan _timeOfDay;
  13. private Timer? _timer;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="DailyTrigger"/> class.
  16. /// </summary>
  17. /// <param name="timeofDay">The time of day to trigger the task to run.</param>
  18. /// <param name="taskOptions">The options of this task.</param>
  19. public DailyTrigger(TimeSpan timeofDay, TaskOptions taskOptions)
  20. {
  21. _timeOfDay = timeofDay;
  22. TaskOptions = taskOptions;
  23. }
  24. /// <summary>
  25. /// Occurs when [triggered].
  26. /// </summary>
  27. public event EventHandler<EventArgs>? Triggered;
  28. /// <summary>
  29. /// Gets the options of this task.
  30. /// </summary>
  31. public TaskOptions TaskOptions { get; }
  32. /// <summary>
  33. /// Stars waiting for the trigger action.
  34. /// </summary>
  35. /// <param name="lastResult">The last result.</param>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="taskName">The name of the task.</param>
  38. /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
  39. public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
  40. {
  41. DisposeTimer();
  42. var now = DateTime.Now;
  43. var triggerDate = now.TimeOfDay > _timeOfDay ? now.Date.AddDays(1) : now.Date;
  44. triggerDate = triggerDate.Add(_timeOfDay);
  45. var dueTime = triggerDate - now;
  46. logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime);
  47. _timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
  48. }
  49. /// <summary>
  50. /// Stops waiting for the trigger action.
  51. /// </summary>
  52. public void Stop()
  53. {
  54. DisposeTimer();
  55. }
  56. /// <summary>
  57. /// Disposes the timer.
  58. /// </summary>
  59. private void DisposeTimer()
  60. {
  61. _timer?.Dispose();
  62. }
  63. /// <summary>
  64. /// Called when [triggered].
  65. /// </summary>
  66. private void OnTriggered()
  67. {
  68. Triggered?.Invoke(this, EventArgs.Empty);
  69. }
  70. }
  71. }