1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-12-23 02:05:27 +02:00
Sonarr/src/NzbDrone.Core/Jobs/Scheduler.cs

80 lines
2.4 KiB
C#
Raw Normal View History

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