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

82 lines
2.7 KiB
C#
Raw Normal View History

2013-05-10 23:53:50 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using NLog;
using NzbDrone.Common.Messaging;
using NzbDrone.Core.Indexers;
using NzbDrone.Core.Lifecycle;
2013-05-13 02:52:55 +00:00
using NzbDrone.Core.MediaFiles.Commands;
using NzbDrone.Core.Providers;
namespace NzbDrone.Core.Jobs
{
public interface ITaskManager
{
IList<ScheduledTask> GetPending();
}
public class TaskManager : IHandle<ApplicationStartedEvent>, IHandleAsync<CommandExecutedEvent>, ITaskManager
{
private readonly IScheduledTaskRepository _scheduledTaskRepository;
private readonly Logger _logger;
public TaskManager(IScheduledTaskRepository scheduledTaskRepository, Logger logger)
{
_scheduledTaskRepository = scheduledTaskRepository;
_logger = logger;
}
public IList<ScheduledTask> GetPending()
{
2013-05-11 05:59:42 +00:00
return _scheduledTaskRepository.All().Where(c => c.LastExecution.AddMinutes(c.Interval) < DateTime.UtcNow).ToList();
}
public void Handle(ApplicationStartedEvent message)
{
var defaultTasks = new[]
{
2013-05-10 23:53:50 +00:00
new ScheduledTask{ Interval = 25, TypeName = typeof(RssSyncCommand).FullName},
2013-05-13 02:52:55 +00:00
new ScheduledTask{ Interval = 12*60, TypeName = typeof(UpdateXemMappings).FullName},
new ScheduledTask{ Interval = 6*60, TypeName = typeof(DiskScanCommand).FullName}
};
var currentTasks = _scheduledTaskRepository.All();
_logger.Debug("Initializing jobs. Available: {0} Existing:{1}", defaultTasks.Count(), currentTasks.Count());
foreach (var job in currentTasks)
{
2013-05-10 23:53:50 +00:00
if (!defaultTasks.Any(c => c.TypeName == job.TypeName))
{
2013-05-10 23:53:50 +00:00
_logger.Debug("Removing job from database '{0}'", job.TypeName);
_scheduledTaskRepository.Delete(job.Id);
}
}
foreach (var defaultTask in defaultTasks)
{
2013-05-10 23:53:50 +00:00
var currentDefinition = currentTasks.SingleOrDefault(c => c.TypeName == defaultTask.TypeName);
if (currentDefinition == null)
{
currentDefinition = defaultTask;
_scheduledTaskRepository.Upsert(currentDefinition);
}
}
}
public void HandleAsync(CommandExecutedEvent message)
{
var scheduledTask = _scheduledTaskRepository.All().SingleOrDefault(c => c.TypeName == message.Command.GetType().FullName);
if (scheduledTask != null)
{
_scheduledTaskRepository.SetLastExecutionTime(scheduledTask.Id, DateTime.UtcNow);
}
}
}
}