I have tried to follow this tutorial on how to create a backgroundworker.
Most of the stuff wasn't useful for me, so I didn't include that. I have no need for a queue. I just need to have this backgroundworker running in the background doing stuff every X hours My worker looks like this. Unfortunately it seems like it never calls the ExecuteAsync method
public class EnergySolutionBackgroundWorker : BackgroundService
{
private readonly ILogger<EnergySolutionBackgroundWorker> _logger;
public EnergySolutionBackgroundWorker(ILogger<EnergySolutionBackgroundWorker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("{Type} is now running in the background.", nameof(BackgroundWorker));
await BackgroundProcessing(stoppingToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogCritical("The {Type} is stopping due to a host shutdown.", nameof(BackgroundWorker));
return base.StopAsync(cancellationToken);
}
private async Task BackgroundProcessing(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await Task.Delay(new TimeSpan(0, 0, 1), stoppingToken);
// Doing some tasks
}
catch (Exception ex)
{
_logger.LogCritical("An error occurred when publishing a book. Exception: {@Exception}", ex);
}
}
}
}
In Startup.cs I have the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHostedService<EnergySolutionBackgroundWorker>();
}
From my understanding, this should be enough for it to automatically start the backgroundworker during startup, but that is not the case. What am I doing wrong?
"{Type} is now running in the background."?// Doing some tasks