繁体   English   中英

.NET CORE中的后台任务调度

[英]Background task scheduling in .NET CORE

我想根据每个请求创建动态cron作业(如果应用程序服务器关闭,后台任务也不会受到影响),并且cron作业可以重新安排或删除。在.net core中实现它的最佳方法是什么。

创建一个新的.net核心控制台应用程序并使用以下模板

在您的Program.cs内部主要方法中(C#级别为7):

public static async Task Main(string[] args)
{  
    var builder = new HostBuilder()
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
        // i needed the input argument for command line, you can use it or simply remove this block
            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }

            Shared.Configuration = config.Build();
        })
        .ConfigureServices((hostContext, services) =>
        {
            // dependency injection

            services.AddOptions();
           // here is the core, where you inject the
           services.AddSingleton<Daemon>();
           services.AddSingleton<IHostedService, MyService>();
        })
        .ConfigureLogging((hostingContext, logging) => {
           // console logging 
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
        });

    await builder.RunConsoleAsync();
}

这是守护程序/服务代码

public class MyService: IHostedService, IDisposable
   {
       private readonly ILogger _logger;
       private readonly Daemon _deamon;

       public MyService(ILogger<MyService> logger, Daemon daemon /* and probably the rest of dependencies*/)
       {
           _logger = logger;         
           _daemon = daemon;  
       }

       public async Task StartAsync(CancellationToken cancellationToken)
       {
           await _deamon.StartAsync(cancellationToken);
       }

       public async Task StopAsync(CancellationToken cancellationToken)
       {
           await _deamon.StopAsync(cancellationToken);
       }

       public void Dispose()
       {
           _deamon.Dispose();
       }
}

这是您想要做的核心,下面的代码是一个模板,您必须提供正确的实现

public class Daemon: IDisposable
   {
       private ILogger<Daemon> _logger;


       protected TaskRunnerBase(ILogger<Daemon> logger)
       {
          _logger = logger;
       }

       public async Task StartAsync(CancellationToken cancellationToken)
       {            
           while (!cancellationToken.IsCancellationRequested)
           {
                await MainAction.DoAsync(cancellationToken); // main job 
            }
       }

       public async Task StopAsync(CancellationToken cancellationToken)
       {
           await Task.WhenAny(MainAction, Task.Delay(-1, cancellationToken));
           cancellationToken.ThrowIfCancellationRequested();
       }

       public void Dispose()
       {
            MainAction.Dispose();
       }
}
  1. 既然您使用的是.NET CORE,就可以在WINDOWSLINUX上同时运行它
  2. 我的.NET核心版本= 2.1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM