2021-09-27 11:47:39 +05:00
|
|
|
|
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;
|
|
|
|
|
|
2021-09-30 16:41:00 +05:00
|
|
|
|
public TelemetryAnalyticsBackgroundService(CacheDb cacheDb)
|
2021-09-27 11:47:39 +05:00
|
|
|
|
{
|
|
|
|
|
this.cacheDb = cacheDb;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken token = default)
|
|
|
|
|
{
|
|
|
|
|
var timeToStartAnalysis = DateTime.Now;
|
|
|
|
|
|
2021-09-29 12:20:19 +05:00
|
|
|
|
while (!token.IsCancellationRequested)
|
2021-09-27 11:47:39 +05:00
|
|
|
|
{
|
|
|
|
|
if(DateTime.Now > timeToStartAnalysis)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2021-09-30 16:41:00 +05:00
|
|
|
|
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);
|
|
|
|
|
|
2021-09-27 11:47:39 +05:00
|
|
|
|
timeToStartAnalysis = DateTime.Now.AddHours(1);
|
|
|
|
|
|
2021-09-30 16:41:00 +05:00
|
|
|
|
await Task.Run(() => analyticsService.CalculateAnalytics(), token)
|
2021-09-27 11:47:39 +05:00
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Trace.TraceError(ex.Message);
|
|
|
|
|
Console.WriteLine(ex.Message);
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-09-29 10:27:49 +05:00
|
|
|
|
|
|
|
|
|
var ms = (int)(timeToStartAnalysis - DateTime.Now).TotalMilliseconds;
|
|
|
|
|
ms = ms > 100 ? ms : 100;
|
|
|
|
|
await Task.Delay(ms, token).ConfigureAwait(false);
|
2021-09-27 11:47:39 +05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override async Task StopAsync(CancellationToken token)
|
|
|
|
|
{
|
|
|
|
|
await base.StopAsync(token).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|