sonarr-repo-only/NzbDrone.Core/Jobs/Scheduler.cs

78 lines
2.4 KiB
C#
Raw Normal View History

2013-05-07 00:39:33 +00:00
using System;
2013-05-22 05:39:46 +00:00
using System.Threading;
using System.Threading.Tasks;
2013-05-10 23:53:50 +00:00
using NLog;
using NzbDrone.Common.Messaging;
using NzbDrone.Core.Lifecycle;
2013-05-22 05:39:46 +00:00
using Timer = System.Timers.Timer;
2013-07-12 06:10:34 +00:00
using NzbDrone.Common.TPL;
namespace NzbDrone.Core.Jobs
{
public class Scheduler :
2013-04-19 04:46:18 +00:00
IHandle<ApplicationStartedEvent>,
IHandle<ApplicationShutdownRequested>
{
private readonly ITaskManager _taskManager;
2013-05-07 00:39:33 +00:00
private readonly IMessageAggregator _messageAggregator;
2013-05-10 23:53:50 +00:00
private readonly Logger _logger;
private static readonly Timer Timer = new Timer();
2013-05-22 05:39:46 +00:00
private static CancellationTokenSource _cancellationTokenSource;
2013-05-10 23:53:50 +00:00
public Scheduler(ITaskManager taskManager, IMessageAggregator messageAggregator, Logger logger)
{
_taskManager = taskManager;
2013-05-07 00:39:33 +00:00
_messageAggregator = messageAggregator;
2013-05-10 23:53:50 +00:00
_logger = logger;
}
public void Handle(ApplicationStartedEvent message)
{
2013-05-22 05:39:46 +00:00
_cancellationTokenSource = new CancellationTokenSource();
Timer.Interval = 1000 * 30;
2013-07-12 06:10:34 +00:00
Timer.Elapsed += (o, args) => Task.Factory.StartNew(ExecuteCommands, _cancellationTokenSource.Token)
.LogExceptions();
Timer.Start();
}
2013-04-19 04:46:18 +00:00
2013-05-07 00:39:33 +00:00
private void ExecuteCommands()
{
try
{
Timer.Enabled = false;
2013-05-07 00:39:33 +00:00
var tasks = _taskManager.GetPending();
2013-05-11 05:59:42 +00:00
_logger.Trace("Pending Tasks: {0}", tasks.Count);
2013-05-10 23:53:50 +00:00
foreach (var task in tasks)
2013-05-10 23:53:50 +00:00
{
2013-05-22 05:39:46 +00:00
_cancellationTokenSource.Token.ThrowIfCancellationRequested();
try
{
2013-05-20 00:30:02 +00:00
_messageAggregator.PublishCommand(task.TypeName);
}
catch (Exception e)
{
_logger.ErrorException("Error occurred while execution task " + task.TypeName, e);
}
}
}
finally
{
2013-05-22 05:39:46 +00:00
if (!_cancellationTokenSource.IsCancellationRequested)
{
Timer.Enabled = true;
}
2013-05-07 00:39:33 +00:00
}
}
2013-04-19 04:46:18 +00:00
public void Handle(ApplicationShutdownRequested message)
{
2013-05-22 05:39:46 +00:00
_cancellationTokenSource.Cancel(true);
Timer.Stop();
2013-04-19 04:46:18 +00:00
}
}
}