首页 > 解决方案 > 如何在 API 中自动调用函数?

问题描述

大家好

我使用 Asp.Net Core 编写了一个 API。我希望一个函数每 10 分钟自动运行一次。我怎么能做这样的事情?

我需要你的帮助 。提前致谢。

public void AutoUpdate()
{
   var startTimeSpan = TimeSpan.Zero;
   var periodTimeSpan = TimeSpan.FromMinutes(10);
   var dbData = _provinceDataDal.GetAll();

   var timer = new System.Threading.Timer((e) =>
   {
     UpdateData(dbData);
   }, null, startTimeSpan, periodTimeSpan);
}

我使用了类似 use 的方法,但它没有按我的意愿工作。因为它只工作一次。

我希望它在上面运行我的 updateData 函数 10 分钟,而不必在 API 首次运行和再次运行时触发它。

标签: c#asp.net-core

解决方案


由于 asp.net core 2.1 是托管服务的后台任务。

一、在Startup中配置服务

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   //Other DI registrations;

   // Register Hosted Services
   services.AddHostedService<MyServices>();
}

之后,使用您想要执行的代码实现 ExecuteAsync 方法

    public class MyServices : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug("Starting");

            stoppingToken.Register(() =>
                _logger.LogDebug("Stopping."));

            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogDebug($"Working");

                // Your code here

                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }

            _logger.LogDebug($"Stopping.");
        }
   }

此链接的 Microsoft中的更多文档


推荐阅读