简体   繁体   English

C# ASP.NET Core - 在已部署的 Web 应用程序/API 中定期/自动运行代码

[英]C# ASP.NET Core - run code periodically/automatically in a deployed web app/API

I'm sure there's a proper term for what I'm trying to do but I don't know it.我确信我正在尝试做的事情有一个适当的术语,但我不知道。 I would like to "run" a program or a method in an API controller periodically.我想定期在 API 控制器中“运行”程序或方法。 For example, in a database connected to my app, I have table A that gets populated from a client request, and table B that uses table A to populate itself.例如,在连接到我的应用程序的数据库中,我有从客户端请求填充的表 A 和使用表 A 填充自身的表 B。 Table B shouldn't be populated during a client request because it would take too long, instead it would be convenient for a program to exist that refers to table A and populates table B periodically.不应该在客户端请求期间填充表 B,因为它会花费太长时间,相反,存在引用表 A 并定期填充表 B 的程序会很方便。

What is this practice called?这种做法叫什么? How is it done in C#/ASP.NET Core and what are some best practices?它是如何在 C#/ASP.NET Core 中完成的,有哪些最佳实践? FYI my ASP.NET Core REST API is deployed in Azure.仅供参考,我的 ASP.NET Core REST API 部署在 Azure 中。

Thank you and stay safe out there!谢谢你,并在那里保持安全!

In ASP.NET Core you can run background tasks by creating a hosted service.在 ASP.NET Core 中,您可以通过创建托管服务来运行后台任务。 You can read the full documentation here .您可以在此处阅读完整的文档。

If you want to run the task periodically then a timed background task may be appropriate.如果您想定期运行任务,那么定时后台任务可能是合适的。 An example taken straight from the documentation is:直接从文档中获取的示例是:

public class TimedHostedService : IHostedService, IDisposable
{
    private int executionCount = 0;
    private readonly ILogger<TimedHostedService> _logger;
    private Timer _timer;

    public TimedHostedService(ILogger<TimedHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service running.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, 
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        var count = Interlocked.Increment(ref executionCount);

        _logger.LogInformation(
            "Timed Hosted Service is working. Count: {Count}", count);
    }

    public Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

Perform your long running task in the DoWork method.DoWork方法中执行长时间运行的任务。 Also note that it says Timer won't wait for your long running task to finish so it may be best to stop the timer first and resume it afterwards.另请注意,它表示Timer不会等待您长时间运行的任务完成,因此最好先停止计时器,然后再恢复它。

Don't forget to register your background task in the ConfigureServices method of your Startup class:不要忘记在Startup类的ConfigureServices方法中注册您的后台任务:

services.AddHostedService<TimedHostedService>();

Architecturally I would suggest you separate those kind of heavy computation into other micro services, or leveraging current serverless capabilities in most cloud offerings.在架构上,我建议您将这些繁重的计算分离到其他微服务中,或者在大多数云产品中利用当前的无服务器功能。

If that's not feasible, asp.net core has something called "background services" which you can leverage to trigger certain tasks.如果这不可行,asp.net core 有一个叫做“后台服务”的东西,你可以利用它来触发某些任务。 Here is the document: Background tasks with hosted services in ASP.NET Core .这是文档: 在 ASP.NET Core 中使用托管服务的后台任务 It's available in 2.1 also.它也可以在 2.1 中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 c#文件更改后如何自动运行asp.net核心应用 - How to run asp.net core app automatically after changes in c# files 自动运行ASP.net c#Web应用程序 - Run ASP.net c# Web Application Automatically 如何使用 ZD7EFA19FBE7D3972FD5ADB6024Z2 在 ASP.NET Core 6 Web API 中运行存储过程? - How run stored procedure in ASP.NET Core 6 Web API using C#? 使用 C# ASP.NET Core Web API 进行谷歌身份验证 - Google authentication with C# ASP.NET Core Web API C# ASP.NET Core Web API 包含与 where - C# ASP.NET Core Web API include with where 身份在 C# ASP.NET 核心 Web API 用户 - Identity in C# ASP.NET Core Web API user ASP.NET Core 2.1,C#应用程序,C#Web服务,访问SQL数据库 - asp.net core 2.1, C# app, c# web service, access SQL database C# Console application wont post large dataset to asp.net .net core 3.0 web api - C# Console application wont post large dataset to asp.net .net core 3.0 web api C# 中的 ASP.NET Core web 应用程序和 VB.net 中的 windows 应用程序组合 - ASP.NET Core web app in C# and windows application in VB.net combination 可以使用按钮来运行cpu密集型代码,然后使用c#和asp.net为Web应用程序显示结果吗? - Can a button be used to run cpu intensive code and then display the results using c# and asp.net for a web app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM