DocSpace-buildtools/common/ASC.Core.Common/Hosting/RegisterInstanceWorkerService.cs

73 lines
2.5 KiB
C#
Raw Normal View History

using System;
using System.Threading;
using System.Threading.Tasks;
2022-02-24 14:15:39 +00:00
using ASC.Common;
using ASC.Common.Logging;
2022-02-24 14:15:39 +00:00
using ASC.Core.Common.Hosting.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
2022-02-24 14:15:39 +00:00
namespace ASC.Core.Common.Hosting;
[Singletone]
2022-02-24 14:15:39 +00:00
public class RegisterInstanceWorkerService<T> : BackgroundService where T : IHostedService
{
private readonly ILog _logger;
2022-02-24 14:15:39 +00:00
private IRegisterInstanceManager<T> _registerInstanceService;
private readonly IHostApplicationLifetime _applicationLifetime;
2022-02-24 14:15:39 +00:00
private readonly IServiceProvider _serviceProvider;
public static readonly string InstanceId =
$"{typeof(T).Name}{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
2022-02-24 14:15:39 +00:00
public RegisterInstanceWorkerService(IOptionsMonitor<ILog> options,
IServiceProvider serviceProvider,
IHostApplicationLifetime applicationLifetime)
{
_logger = options.CurrentValue;
_serviceProvider = serviceProvider;
_applicationLifetime = applicationLifetime;
2022-02-24 14:15:39 +00:00
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _serviceProvider.CreateScope();
2022-02-24 14:15:39 +00:00
_registerInstanceService = scope.ServiceProvider.GetService<IRegisterInstanceManager<T>>();
while (!stoppingToken.IsCancellationRequested)
{
try
{
2022-02-24 14:15:39 +00:00
await _registerInstanceService.Register(InstanceId);
await _registerInstanceService.DeleteOrphanInstances();
_logger.InfoFormat("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
catch (Exception ex)
{
_logger.ErrorFormat("Critical error forced worker to shutdown", ex);
_applicationLifetime.StopApplication();
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
try
{
2022-02-24 14:15:39 +00:00
await _registerInstanceService.UnRegister(InstanceId);
_logger.InfoFormat("UnRegister Instance {instanceName} running at: {time}.", InstanceId, DateTimeOffset.Now);
}
catch
{
2022-02-24 14:15:39 +00:00
_logger.ErrorFormat("Unable to UnRegister Instance {instanceName} running at: {time}.", InstanceId, DateTimeOffset.Now);
}
await base.StopAsync(cancellationToken);
}
}