using System;
using System.Threading;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
{
///
/// Represents a task trigger that fires on a weekly basis
///
public class WeeklyTrigger : ITaskTrigger
{
///
/// Get the time of day to trigger the task to run
///
/// The time of day.
public TimeSpan TimeOfDay { get; set; }
///
/// Gets or sets the day of week.
///
/// The day of week.
public DayOfWeek DayOfWeek { get; set; }
///
/// Gets the execution properties of this task.
///
///
/// The execution properties of this task.
///
public TaskExecutionOptions TaskOptions { get; set; }
///
/// Gets or sets the timer.
///
/// The timer.
private Timer Timer { get; set; }
///
/// Stars waiting for the trigger action
///
/// The last result.
/// 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()
{
if (Timer != null)
{
Timer.Dispose();
}
}
///
/// Occurs when [triggered].
///
public event EventHandler> Triggered;
///
/// Called when [triggered].
///
private void OnTriggered()
{
if (Triggered != null)
{
Triggered(this, new GenericEventArgs(TaskOptions));
}
}
}
}