首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在.NET核中通过cron作业实现后台任务调度

如何在.NET核中通过cron作业实现后台任务调度
EN

Stack Overflow用户
提问于 2018-12-03 11:41:11
回答 1查看 3.1K关注 0票数 1

我希望根据每个请求创建一个动态的cron作业(如果应用服务器关机,不应该影响后台任务),并且可以重新安排或删除cron作业。如何在.NET核心中实现这一点?

EN

回答 1

Stack Overflow用户

发布于 2018-12-03 14:27:49

创建一个新的.NET核心控制台应用程序,并在主方法(使用C# 7)内的Program.cs中使用以下模板:

代码语言:javascript
复制
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();
}

下面是守护进程/服务代码

代码语言:javascript
复制
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();
       }
}

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

代码语言:javascript
复制
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核心
  2. 我的.NET核心版本是2.1。
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53593113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档