using MediaBrowser.Model.Events;
using MediaBrowser.Model.Tasks;
using System;
using System.Linq;
using System.Threading;
namespace MediaBrowser.Common.ScheduledTasks
{
///
/// Represents a task trigger that runs repeatedly on an interval
///
public class IntervalTrigger : ITaskTrigger
{
///
/// Gets or sets the interval.
///
/// The interval.
public TimeSpan Interval { 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; }
private DateTime _lastStartDate;
///
/// Stars waiting for the trigger action
///
/// The last result.
/// if set to true [is application startup].
public void Start(TaskResult lastResult, bool isApplicationStartup)
{
DisposeTimer();
DateTime triggerDate;
if (lastResult == null)
{
// Task has never been completed before
triggerDate = DateTime.UtcNow.AddHours(1);
}
else
{
triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate }.Max().Add(Interval);
}
if (DateTime.UtcNow > triggerDate)
{
triggerDate = DateTime.UtcNow.AddMinutes(1);
}
Timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.UtcNow, 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()
{
DisposeTimer();
if (Triggered != null)
{
_lastStartDate = DateTime.UtcNow;
Triggered(this, new GenericEventArgs(TaskOptions));
}
}
}
}