.NET CORE中的后台任务调度

时间:2018-12-03 11:41:11

标签: c# .net core

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

1 个答案:

答案 0 :(得分:3)

创建一个新的.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. 您可以同时在 WINDOWS LINUX 上运行它,因为您正在使用.NET CORE
  2. 我的.NET CORE 版本= 2.1
相关问题