DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/TelemetryAnalyticsBackgroundService.cs

66 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudDb.Model;
namespace AsbCloudInfrastructure.Services
{
public class TelemetryAnalyticsBackgroundService : BackgroundService
{
private readonly CacheDb cacheDb;
public TelemetryAnalyticsBackgroundService(CacheDb cacheDb)
{
this.cacheDb = cacheDb;
}
protected override async Task ExecuteAsync(CancellationToken token = default)
{
var timeToStartAnalysis = DateTime.Now;
while (!token.IsCancellationRequested)
{
if(DateTime.Now > timeToStartAnalysis)
{
try
{
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
.UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
.Options;
using var context = new AsbCloudDbContext(options);
var telemetryService = new TelemetryService(context, cacheDb);
var analyticsService = new TelemetryAnalyticsService(context,
telemetryService, cacheDb);
timeToStartAnalysis = DateTime.Now.AddHours(1);
await Task.Run(() => analyticsService.CalculateAnalytics(), token)
.ConfigureAwait(false);
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
Console.WriteLine(ex.Message);
}
}
var ms = (int)(timeToStartAnalysis - DateTime.Now).TotalMilliseconds;
ms = ms > 100 ? ms : 100;
await Task.Delay(ms, token).ConfigureAwait(false);
}
}
public override async Task StopAsync(CancellationToken token)
{
await base.StopAsync(token).ConfigureAwait(false);
}
}
}