简体   繁体   English

如何每隔 X 小时自动调用 ASP.NET Core 端点?

[英]How can I automatically call an ASP.NET Core endpoint each X hours?

I've build an API with ASP.NET Core.我用 ASP.NET Core 构建了一个 API。 Some of my controllers have an endpoint, which need to run each X hours.我的一些控制器有一个端点,需要每 X 小时运行一次。 Nevertheless I still want to be able to call the endpoint by my own at any time.尽管如此,我仍然希望能够随时自己调用端点。

The endpoints all have the same structure:端点都具有相同的结构:

[RequireHttps, HttpGet("/generate")]
public async Task<IActionResult> GenerateFiles()
{
    // do stuff 
}

Does anybody know how I could achieve this in ASP.NET Core itself without any third-party tool?有谁知道我如何在没有任何第三方工具的情况下在 ASP.NET Core 中实现这一点? I thought of using a timer, but I feel like this is not the best way to do so.我想过使用计时器,但我觉得这不是最好的方法。 I highly appreciate any kind of help, cheers: :)我非常感谢任何形式的帮助,干杯::)

With Hangfire that's quite easy to do:使用Hangfire这很容易做到:

Inside the Program.cs/Startup.cs:在 Program.cs/Startup.cs 中:

builder.Services
    .AddHangfire(opts => opts
        .UseSqlServerStorage(config
            .GetSection(nameof(HangfireConfig))
            .Get<HangfireConfig>()
            .ConnectionString)
        .AddUpdateJob(builder.Environment))
    .AddHangfireServer()

And AddUpdateJob() is implemented like this:AddUpdateJob()是这样实现的:

public static IGlobalConfiguration AddUpdateJob(
    this IGlobalConfiguration opts,
    IWebHostEnvironment env)
{
    if (!env.IsEnvironment("Local"))
    {
        RecurringJob.AddOrUpdate<IMasterDataUpdater>(
            "masterdata-update",
            x => x.Update(),
            Cron.Hourly);
    }

    return otps;
}

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

相关问题 ASP.Net Core 6,SPA,端点 - 我无法从 http 调用 controller 获取请求 - ASP.Net Core 6, SPA, endpoint - I can't call a controller from http get request 如何在 ASP.NET Core MVC 中调用具有 HttpDelete 属性的端点? - How to call an endpoint with HttpDelete attribute in ASP.NET Core MVC? 如何在 asp.net 内核中创建端点,接受多个文件,每个文件都有一个文本链接? - How create endpoint in asp.net core accepting multiple files with a text linked to each file? 如何在使用 ASP.NET 核心中间件健康检查创建的健康检查端点上有选择地强制执行 HTTPS? - How can I selectively enforce HTTPS on a health check endpoint created using ASP.NET Core Middleware Health Checks? 如何使用X509SecurityKey进行Asp.Net Core JWT验证? - How can I use X509SecurityKey for Asp.Net Core JWT validation? 如何在 3.x 中取回 ASP.NET 核心详细请求登录 - How can I get back ASP.NET Core verbose request logging in 3.x 如何在新的ASP.NET Core中调用Web API非默认构造函数 - How can I call Web API non-default constructor in new ASP.NET Core ASP.NET Core 无法进入端点方法? - ASP.NET Core can't step into endpoint method? 我可以从 ASP.Net Web API 调用 WCF 端点吗? - Can I call a WCF endpoint from ASP.Net Web API? 如何在我上传文件的Asp.Net核心web api端点上进行集成测试? - How to do an integration test on my Asp.Net core web api endpoint where I upload a file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM