using System;
using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
///
/// Represents a task trigger that fires on a weekly basis.
///
public sealed class WeeklyTrigger : ITaskTrigger
{
private readonly TimeSpan _timeOfDay;
private readonly DayOfWeek _dayOfWeek;
private Timer? _timer;
///
/// Initializes a new instance of the class.
///
/// The time of day to trigger the task to run.
/// The day of week.
/// The options of this task.
public WeeklyTrigger(TimeSpan timeofDay, DayOfWeek dayOfWeek, TaskOptions taskOptions)
{
_timeOfDay = timeofDay;
_dayOfWeek = dayOfWeek;
TaskOptions = taskOptions;
}
///
/// Occurs when [triggered].
///
public event EventHandler? Triggered;
///
/// Gets the options of this task.
///
public TaskOptions TaskOptions { get; }
///
/// Stars waiting for the trigger action.
///
/// The last result.
/// The logger.
/// The name of the task.
/// if set to true [is application startup].
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{
DisposeTimer();
var triggerDate = GetNextTriggerDateTime();
_timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
}
///
/// Gets the next trigger date time.
///
/// DateTime.
private DateTime GetNextTriggerDateTime()
{
var now = DateTime.Now;
// If it's on the same day
if (now.DayOfWeek == _dayOfWeek)
{
// It's either later today, or a week from now
return now.TimeOfDay < _timeOfDay ? now.Date.Add(_timeOfDay) : now.Date.AddDays(7).Add(_timeOfDay);
}
var triggerDate = now.Date;
// Walk the date forward until we get to the trigger day
while (triggerDate.DayOfWeek != _dayOfWeek)
{
triggerDate = triggerDate.AddDays(1);
}
// Return the trigger date plus the time offset
return triggerDate.Add(_timeOfDay);
}
///
/// Stops waiting for the trigger action.
///
public void Stop()
{
DisposeTimer();
}
///
/// Disposes the timer.
///
private void DisposeTimer()
{
_timer?.Dispose();
}
///
/// Called when [triggered].
///
private void OnTriggered()
{
Triggered?.Invoke(this, EventArgs.Empty);
}
}
}