added cancellation token to Scheduler.

This commit is contained in:
kay.one 2013-05-21 22:39:46 -07:00
parent 4ad7ce8363
commit 028bd5251c
1 changed files with 13 additions and 3 deletions

View File

@ -1,9 +1,11 @@
using System; using System;
using System.Timers; using System.Threading;
using System.Threading.Tasks;
using NLog; using NLog;
using NzbDrone.Common.Composition; using NzbDrone.Common.Composition;
using NzbDrone.Common.Messaging; using NzbDrone.Common.Messaging;
using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Lifecycle;
using Timer = System.Timers.Timer;
namespace NzbDrone.Core.Jobs namespace NzbDrone.Core.Jobs
{ {
@ -16,6 +18,7 @@ namespace NzbDrone.Core.Jobs
private readonly IMessageAggregator _messageAggregator; private readonly IMessageAggregator _messageAggregator;
private readonly Logger _logger; private readonly Logger _logger;
private static readonly Timer Timer = new Timer(); private static readonly Timer Timer = new Timer();
private static CancellationTokenSource _cancellationTokenSource;
public Scheduler(ITaskManager taskManager, IMessageAggregator messageAggregator, Logger logger) public Scheduler(ITaskManager taskManager, IMessageAggregator messageAggregator, Logger logger)
{ {
@ -26,8 +29,9 @@ namespace NzbDrone.Core.Jobs
public void Handle(ApplicationStartedEvent message) public void Handle(ApplicationStartedEvent message)
{ {
_cancellationTokenSource = new CancellationTokenSource();
Timer.Interval = 1000 * 30; Timer.Interval = 1000 * 30;
Timer.Elapsed += (o, args) => ExecuteCommands(); Timer.Elapsed += (o, args) => Task.Factory.StartNew(ExecuteCommands, _cancellationTokenSource.Token);
Timer.Start(); Timer.Start();
} }
@ -43,6 +47,8 @@ namespace NzbDrone.Core.Jobs
foreach (var task in tasks) foreach (var task in tasks)
{ {
_cancellationTokenSource.Token.ThrowIfCancellationRequested();
try try
{ {
_messageAggregator.PublishCommand(task.TypeName); _messageAggregator.PublishCommand(task.TypeName);
@ -55,12 +61,16 @@ namespace NzbDrone.Core.Jobs
} }
finally finally
{ {
Timer.Enabled = true; if (!_cancellationTokenSource.IsCancellationRequested)
{
Timer.Enabled = true;
}
} }
} }
public void Handle(ApplicationShutdownRequested message) public void Handle(ApplicationShutdownRequested message)
{ {
_cancellationTokenSource.Cancel(true);
Timer.Stop(); Timer.Stop();
} }
} }