jellyfin/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs

89 lines
2.6 KiB
C#
Raw Normal View History

2016-10-29 05:40:15 +00:00
using System;
using System.Globalization;
using System.Threading;
using MediaBrowser.Model.Events;
using Microsoft.Extensions.Logging;
2016-10-29 05:40:15 +00:00
using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks
2016-10-29 05:40:15 +00:00
{
/// <summary>
/// Represents a task trigger that fires everyday
/// </summary>
public class DailyTrigger : ITaskTrigger
{
/// <summary>
/// Get the time of day to trigger the task to run
/// </summary>
/// <value>The time of day.</value>
public TimeSpan TimeOfDay { get; set; }
/// <summary>
2018-09-12 17:26:21 +00:00
/// Gets or sets the options of this task.
2016-10-29 05:40:15 +00:00
/// </summary>
2018-09-12 17:26:21 +00:00
public TaskOptions TaskOptions { get; set; }
2016-10-29 05:40:15 +00:00
/// <summary>
2018-09-12 17:26:21 +00:00
/// Gets or sets the timer.
2016-10-29 05:40:15 +00:00
/// </summary>
2018-09-12 17:26:21 +00:00
/// <value>The timer.</value>
private Timer Timer { get; set; }
2016-10-29 05:40:15 +00:00
/// <summary>
/// Stars waiting for the trigger action
/// </summary>
/// <param name="lastResult">The last result.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
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.LogInformation("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
2016-10-29 05:40:15 +00:00
Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
}
/// <summary>
/// Stops waiting for the trigger action
/// </summary>
public void Stop()
{
DisposeTimer();
}
/// <summary>
/// Disposes the timer.
/// </summary>
private void DisposeTimer()
{
if (Timer != null)
{
Timer.Dispose();
}
}
/// <summary>
/// Occurs when [triggered].
/// </summary>
2018-09-12 17:26:21 +00:00
public event EventHandler<EventArgs> Triggered;
2016-10-29 05:40:15 +00:00
/// <summary>
/// Called when [triggered].
/// </summary>
private void OnTriggered()
{
if (Triggered != null)
{
2018-09-12 17:26:21 +00:00
Triggered(this, EventArgs.Empty);
2016-10-29 05:40:15 +00:00
}
}
}
}