wabbajack/Wabbajack.Server/Services/AbstractService.cs

67 lines
1.8 KiB
C#
Raw Normal View History

2020-05-13 21:52:34 +00:00
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using Wabbajack.BuildServer;
namespace Wabbajack.Server.Services
{
public interface IStartable
{
public void Start();
}
public abstract class AbstractService<TP, TR> : IStartable
{
protected AppSettings _settings;
private TimeSpan _delay;
protected ILogger<TP> _logger;
protected QuickSync _quickSync;
2020-05-13 21:52:34 +00:00
public AbstractService(ILogger<TP> logger, AppSettings settings, QuickSync quickSync, TimeSpan delay)
2020-05-13 21:52:34 +00:00
{
_settings = settings;
_delay = delay;
_logger = logger;
_quickSync = quickSync;
2020-05-13 21:52:34 +00:00
}
public void Start()
{
if (_settings.RunBackEndJobs)
{
Task.Run(async () =>
{
while (true)
{
await _quickSync.ResetToken<TP>();
2020-05-13 21:52:34 +00:00
try
{
await Execute();
}
catch (Exception ex)
{
_logger.LogError(ex, "Running Service Loop");
}
var token = await _quickSync.GetToken<TP>();
await Task.Delay(_delay, token);
2020-05-13 21:52:34 +00:00
}
});
}
}
public abstract Task<TR> Execute();
}
public static class AbstractServiceExtensions
{
public static void UseService<T>(this IApplicationBuilder b)
{
var poll = (IStartable)b.ApplicationServices.GetService(typeof(T));
poll.Start();
}
}
}