在 ASP.NET Web API 中创建一个线程每隔 X 秒执行一次特定代码

Make a thread to execute certain code every X seconds, in ASP.NET Web API

我需要在我的 C# Net Core WebApi 的单独线程中执行某些调用。我一直在查看一些文档,但没有找到适合我需要的内容。

我有这个代码作为我的Program.cs(用于测试海豚)但我没有用:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;

namespace backend
{
    public class Program
    {
       
        public static void Main(string[] args)
        {
            Timer timer = new Timer(1000);
            timer.AutoReset = true;
            timer.Elapsed += new ElapsedEventHandler(test);
            timer.Start();
            CreateHostBuilder(args).Build().Run();
            
        }
        public static void test(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Look mom, I'm on a thread.");

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

我对这个话题有点陌生。有任何提示或想法吗?

我已经解决了这个 documentation。我已经创建了一个后台服务并添加到来自 Startup.cs 的服务中。

文档:

Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            /*...*/
            services.AddHostedService<TimedBackgroundService>();
            /*...*/
        }

Program.cs

namespace backend
{
    public class Program
    {
       
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            
        }
        

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

TimedBackgroundService.cs

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace backend
{
    public class TimedBackgroundService:IHostedService, IDisposable
    {
        private int executionCount = 0;
        private readonly ILogger<TimedBackgroundService> _logger;
        private Timer _timer;
        public TimedBackgroundService(ILogger<TimedBackgroundService> 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)
        {
            Console.WriteLine("I'm working on a background Service");
        }
        public void Dispose()
        {
            _timer?.Dispose();
        }
        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");

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

            return Task.CompletedTask;
        }
    }
}