I've created a program in Worker Service template which is downloading Temperature from web API with specific temperature sensor parameters. After that im saving these parameters to the SQL database which i created with EF. Every 10 sec i downloding new measurement from API. The main problem is when im trying to run this program as background service. Service is starting and running but not executing my code.
Program.cs code:
using Microsoft.EntityFrameworkCore;
using TemperatureService.Entities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace TemperatureService
{
public class Program
{
static async Task Main(string[] args)
{
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
})
.ConfigureServices(services =>
{
IConfiguration configuration = services.BuildServiceProvider().GetService<IConfiguration>();
services.AddHostedService<Worker>();
})
.UseWindowsService()
.Build();
await host.RunAsync();
}
}
}
Worker.cs code:
using TemperatureService.Entities;
using Newtonsoft.Json.Linq;
using System.Globalization;
namespace TemperatureService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly TemperatureDbContext _dbContext;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
_dbContext = new TemperatureDbContext();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) => Task.Run(async () =>
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
string apiUrl = "http://10.10.30.249/state";
// Step 1: Download JSON data from API
var json = await GetTemperatureAsync(apiUrl);
// Step 2: Deserialize JSON into C# objects
var responseJson = JObject.Parse(json);
// Step 3: Extract the temperature value from the first item in the "sensors" array
var sensorsArray = responseJson["multiSensor"]["sensors"];
Console.WriteLine(sensorsArray);
var timestampStr = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
var timestampFormat = "MM/dd/yyyy HH:mm:ss";
var timestamp = DateTime.ParseExact(timestampStr, timestampFormat, CultureInfo.InvariantCulture);
// Step 4: Create a new TemperatureSensorData object and set its properties
var sensorData = new TemperatureSensorData
{
Value = (double)sensorsArray[0]["value"] / 100,
Trend = (int)sensorsArray[0]["trend"],
State = (int)sensorsArray[0]["state"],
ElapsedTimeS = (int)sensorsArray[0]["elapsedTimeS"],
TimeStamp = timestamp,
IpAddress = "10.10.30.249"
};
// Step 5: Add the new sensor data to the database
_dbContext.Temperatures.Add(sensorData);
await _dbContext.SaveChangesAsync();
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
catch (Exception ex)
{
Console.WriteLine($"Error downloading temperature: {ex.Message}");
}
}
});
private async Task<string> GetTemperatureAsync(string url)
{
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
Console.WriteLine(response);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}