using System;
using System.Threading.Tasks;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks
{
///
/// Class SystemEventTrigger
///
public class SystemEventTrigger : ITaskTrigger
{
///
/// Gets or sets the system event.
///
/// The system event.
public SystemEvent SystemEvent { get; set; }
///
/// Gets or sets the options of this task.
///
public TaskOptions TaskOptions { get; set; }
private readonly ISystemEvents _systemEvents;
public SystemEventTrigger(ISystemEvents systemEvents)
{
_systemEvents = systemEvents;
}
///
/// 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)
{
switch (SystemEvent)
{
case SystemEvent.WakeFromSleep:
_systemEvents.Resume += _systemEvents_Resume;
break;
}
}
private async void _systemEvents_Resume(object sender, EventArgs e)
{
if (SystemEvent == SystemEvent.WakeFromSleep)
{
// This value is a bit arbitrary, but add a delay to help ensure network connections have been restored before running the task
await Task.Delay(10000).ConfigureAwait(false);
OnTriggered();
}
}
///
/// Stops waiting for the trigger action
///
public void Stop()
{
_systemEvents.Resume -= _systemEvents_Resume;
}
///
/// Occurs when [triggered].
///
public event EventHandler Triggered;
///
/// Called when [triggered].
///
private void OnTriggered()
{
if (Triggered != null)
{
Triggered(this, EventArgs.Empty);
}
}
}
}