[英]How to start BackgroundService in ASP.Net core 3.1 API
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.我只需要让这个 backgroundworker 在后台运行,每 X 小时做一次事情我的工人看起来像这样。 Unfortunately it seems like it never calls the ExecuteAsync method不幸的是,它似乎从不调用 ExecuteAsync 方法
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:在 Startup.cs 我有以下内容:
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.根据我的理解,这应该足以让它在启动期间自动启动 backgroundworker,但事实并非如此。 What am I doing wrong?我究竟做错了什么?
internal class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is starting.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
I believe I found the answer.我相信我找到了答案。 Startup.cs is not run before the first call to the API is made, After calling a simple Test method in one of my controllers, the BackgroundProcessing method was called That's a bit annoying, as I was hoping I later could create a backgroundworker that loads a lot of data into memory instead of it happening when the first call is made在第一次调用 API 之前 Startup.cs 没有运行,在我的一个控制器中调用了一个简单的测试方法之后,调用了 BackgroundProcessing 方法这有点烦人,因为我希望以后可以创建一个加载的后台工作程序很多数据进入 memory 而不是在第一次调用时发生
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.