using System;
using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks.Triggers
{
///
/// Represents a task trigger that fires on a weekly basis.
///
public sealed class WeeklyTrigger : ITaskTrigger, IDisposable
{
private readonly TimeSpan _timeOfDay;
private readonly DayOfWeek _dayOfWeek;
private Timer? _timer;
private bool _disposed = false;
///
/// 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(_ => 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();
_timer = null;
}
///
/// Called when [triggered].
///
private void OnTriggered()
{
Triggered?.Invoke(this, EventArgs.Empty);
}
///
public void Dispose()
{
if (_disposed)
{
return;
}
DisposeTimer();
_disposed = true;
}
}
}