using System;
using System.Globalization;
using System.Threading;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Tasks;
namespace Emby.Common.Implementations.ScheduledTasks
{
///
/// Represents a task trigger that fires everyday
///
public class DailyTrigger : 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 timer.
///
/// The timer.
private Timer Timer { get; set; }
///
/// Gets the execution properties of this task.
///
///
/// The execution properties of this task.
///
public TaskExecutionOptions TaskOptions { 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 now = DateTime.Now;
var triggerDate = now.TimeOfDay > TimeOfDay ? now.Date.AddDays(1) : now.Date;
triggerDate = triggerDate.Add(TimeOfDay);
var dueTime = triggerDate - now;
logger.Info("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
}
///
/// 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));
}
}
}
}