.NET CORE 中的后台任务调度

Tej*_*yan 1 .net c# core

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

Moh*_*deh 6

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

在你 Program.cs 里面的 main 方法(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();
}
Run Code Online (Sandbox Code Playgroud)

这是守护进程/服务代码

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();
       }
}
Run Code Online (Sandbox Code Playgroud)

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

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();
       }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您可以在WINDOWSLINUX 上运行它,因为您使用的是 .NET Core
  2. 我的 .NET 核心版本 = 2.1