简体   繁体   English

ASP.Net core 3.1中如何启动BackgroundService API

[英]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?我究竟做错了什么?

  1. you can add timer in start function. A timed background task makes use of the System.Threading.Timer class. The timer triggers the task's DoWork method.您可以在开始时添加计时器 function。定时后台任务使用 System.Threading.Timer class。计时器触发任务的 DoWork 方法。 The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:计时器在 StopAsync 上被禁用,并在服务容器在 Dispose 上被释放时被释放:
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();
    }
}
  1. there is a reference有一个参考

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.

相关问题 有没有办法在 Asp.Net core 3.1 中手动启动 BackgroundService - Is there a way to manually start BackgroundService in Asp.Net core 3.1 在ASP.NET Core中启动BackgroundService的正确方法 - Correct way to start a BackgroundService in ASP.NET Core .NET 5 WindowsService with ASP.NET Core and BackgroundService - .NET 5 WindowsService with ASP.NET Core and BackgroundService 如何在 ASP.net 内核中手动取消 BackgroundService - How to cancel manually a BackgroundService in ASP.net core 如何在 ASP.NET Core 2.1 中的计时器上运行 BackgroundService - How to run BackgroundService on a timer in ASP.NET Core 2.1 如何手动重启 ASP.net 核心中的 BackgroundService - How to restart manually a BackgroundService in ASP.net core 使用 ASP.NET 核心 6 最小 ZDB93474238D104CAADE1 停止 Azure 中的 Web 应用程序时未调用 BackgroundService StopAsync - BackgroundService StopAsync not called when stopping Web App in Azure using ASP.NET Core 6 Minimal API 从asp.net core 2.1中的控制器访问BackgroundService - access BackgroundService from controller in asp.net core 2.1 在 ASP.NET Core 中处理 BackgroundService 中的非托管回调 - Handle unmanaged callback in BackgroundService in ASP.NET Core ASP.Net Core BackgroundService被无故取消 - ASP.Net Core BackgroundService is cancelled without reason
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM