ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.NET Core 中基于 IHostedService 实现后台定时任务

2021-12-19 18:32:15  阅读:143  来源: 互联网

标签:BackgroundServiceSample Core TimedBackgroundService 2018 Services World NET IHos


https://www.cnblogs.com/dudu/p/9647619.html

 

.NET Core 2.0 引入了 IHostedService ,基于它可以很方便地执行后台任务,.NET Core 2.1 则锦上添花地提供了 IHostedService 的默认实现基类 BackgroundService ,在这篇随笔中分别用 Web 与 Console 程序体验一下。

首先继承 BackgroundService 实现一个 TimedBackgroundService

public class TimedBackgroundService : BackgroundService
{
    private readonly ILogger _logger;
    private Timer _timer;

    public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation($"Hello World! - {DateTime.Now}");
    }

    public override void Dispose()
    {
        base.Dispose();
        _timer?.Dispose();
    }
}

在 ASP.NET Core Web 程序中执行这个后台定时任务只需在 Startup 的 ConfigureServices 注册 TimedBackgroundService 即可:

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

然后只要站点启动,就会定时输出日志:

Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:48:02
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:48:07
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:48:12

接下来在控制台程序中体验一下。
基于 Generic Host 实现如下的控制台程序,也是执行在 ConfigureServices 中注册一下 TimedBackgroundService 。

class Program
{
    public static async Task Main(string[] args)
    {
        var builder = new HostBuilder()
            .ConfigureLogging(logging =>
            {
                logging.AddConsole();
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<TimedBackgroundService>();
            });

        await builder.RunConsoleAsync();
    }
}

dotnet run 运行程序后 TimedBackgroundService 定时输出了日志:

info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:59:37
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:59:42
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:59:47

体验完成。

标签:BackgroundServiceSample,Core,TimedBackgroundService,2018,Services,World,NET,IHos
来源: https://www.cnblogs.com/Insist-Y/p/15708088.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有