zoukankan      html  css  js  c++  java
  • 2019-8-31-ASP.NET-Core-开启后台任务

    title author date CreateTime categories
    ASP.NET Core 开启后台任务
    lindexi
    2019-08-31 16:55:58 +0800
    2019-3-9 15:18:2 +0800
    asp aspdotnetcore dotnetcore

    本文告诉大家如何通过 Microsoft.Extensions.Hosting.BackgroundService 开启后台任务

    实现 BackManagerService 类继承 BackgroundService 抽象类,请看代码

        public class BackManagerService : BackgroundService
        {
            /// <inheritdoc />
            protected override Task ExecuteAsync(CancellationToken stoppingToken)
            {
                return Task.CompletedTask;
            }
        }

    然后打开 Startup.cs 在 ConfigureServices 方法注入

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddSingleton<IHostedService, BackManagerService>();
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }

    现在运行 ASP.NET Core 程序就可以看到调用进 ExecuteAsync 方法了

    那么如何实现轮询?大概在30秒左右做某个任务?在没有用任何设计的情况,假如这个任务就放在了 BackManagerService 的 Foo 方法,可以通过下面代码调用

            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    Foo();
                    await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
                }
            }

    通过 Task.Delay 的方法延迟指定的时间就可以了,那么更复杂的封装就在大佬们的封装变得更加好用,更多封装请看 Ron 大佬博客

    所有代码放在 github

    Asp.Net Core 轻松学-基于微服务的后台任务调度管理器 - Ron.Liang - 博客园

    在 ASP.NET Core 中使用托管服务实现后台任务

  • 相关阅读:
    docker使用
    window版docker安装及配置
    mysql命令
    xshell
    git 命令
    分页器原理
    PCL-Kinfu编译手册
    cmake-add_definitions
    cmake-include_directories
    cmake-source_group
  • 原文地址:https://www.cnblogs.com/lindexi/p/12086413.html
Copyright © 2011-2022 走看看