using System;
using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks.Triggers
{
///
/// Represents a task trigger that fires everyday.
///
public sealed class DailyTrigger : ITaskTrigger, IDisposable
{
private readonly TimeSpan _timeOfDay;
private Timer? _timer;
private bool _disposed = false;
///
/// Initializes a new instance of the class.
///
/// The time of day to trigger the task to run.
/// The options of this task.
public DailyTrigger(TimeSpan timeofDay, TaskOptions taskOptions)
{
_timeOfDay = timeofDay;
TaskOptions = taskOptions;
}
///
/// Occurs when [triggered].
///
public event EventHandler? Triggered;
///
/// Gets the options of this task.
///
public TaskOptions TaskOptions { get; }
///
/// Stars waiting for the trigger action.
///
/// The last result.
/// The logger.
/// The name of the task.
/// 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.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime);
_timer = new Timer(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
}
///
/// Stops waiting for the trigger action.
///
public void Stop()
{
DisposeTimer();
}
///
/// Disposes the timer.
///
private void DisposeTimer()
{
_timer?.Dispose();
_timer = null;
}
///
/// Called when [triggered].
///
private void OnTriggered()
{
Triggered?.Invoke(this, EventArgs.Empty);
}
///
public void Dispose()
{
if (_disposed)
{
return;
}
DisposeTimer();
_disposed = true;
}
}
}