using MediaBrowser.Model.Events;
using MediaBrowser.Model.Tasks;
using System;
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; }
///
/// Gets or sets the first run delay.
///
/// The first run delay.
public TimeSpan FirstRunDelay { get; set; }
public IntervalTrigger()
{
FirstRunDelay = TimeSpan.FromHours(1);
}
///
/// Stars waiting for the trigger action
///
/// The last result.
/// if set to true [is application startup].
public void Start(TaskResult lastResult, bool isApplicationStartup)
{
DisposeTimer();
var triggerDate = lastResult != null ?
lastResult.EndTimeUtc.Add(Interval) :
DateTime.UtcNow.Add(FirstRunDelay);
if (DateTime.UtcNow > triggerDate)
{
if (isApplicationStartup)
{
triggerDate = DateTime.UtcNow.AddMinutes(1);
}
else
{
triggerDate = DateTime.UtcNow.Add(Interval);
}
}
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()
{
if (Triggered != null)
{
Triggered(this, new GenericEventArgs(TaskOptions));
}
}
}
}