Zengjing

by Zengjing 2019-04-14

.Net Core构建后台定时服务

在.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)
        {
        }

        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
        }
}

至此,一个定时任务服务已经开发完成,赶紧去试试吧。

收获点赞: 0

评论

...