.Net Core通过BackgroundServer构建后台服务

慕承允
2023-12-01

在.Net Core2.1版本中,新增了一个名为BackgroundService的类,隶属于Microsoft.Extensions.Hosting命名空间,用来创建后台任务服务,比如定时推送数据与接收消息等。现在我们来实现一个简单的定时任务。

注册服务

首先我们先在Startup中注册该服务。

services.AddSingleton<IHostedService,TimedExecutService>()

其中TimedExecutService是我们基于继承BackgroundService新建的定时任务类。

实现接口

BackgroundService接口提供了三个方法,分别是ExecuteAsync(CancellationToken),StartAsync(CancellationToken),StopAsync(CancellationToken)。TimedExecutService可以通过重载这三个方法来实现业务开发。

public class TimedExecutService : BackgroundService
{       
    private readonly ILogger<TimedExecutService> _logger;
    private readonly TimedExecutServiceSettings _settings;
 
    public TimedExecutService(IOptions<TimedExecutServiceSettings> settings, ILogger<TimedExecutService> logger)
        {
            //Constructor’s parameters validations   
        }
 
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug($"TimedExecutService is starting.");
            stoppingToken.Register(() => _logger.LogDebug($"TimedExecutService is stopping."));
 
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogDebug($"TimedExecutService doing background work.");
                //Doing Somethings
                await Task.Delay(_settings.CheckUpdateTime, stoppingToken);
            }
         
            _logger.LogDebug($"TimedExecutService is stopping.");
        }
 
        protected override async Task StopAsync (CancellationToken stoppingToken)
        {
               // Doing Somethings
        }
}
 类似资料: