【问题标题】:Run BackgroundService every day at midnight in .Net Core 3.0在 .Net Core 3.0 中每天午夜运行 BackgroundService
【发布时间】:2020-02-13 05:58:50
【问题描述】:

我想每天在午夜运行后台服务。 .NET Core 默认的 BackgroundService 在task.delay 上运行,我想每半夜(24 小时间隔)运行一次。

我在每个 task.Delay 间隔而不是指定的特定时间运行 BackgroundService 的问题。

public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly IServiceScopeFactory _serviceScopeFactory;

        public Worker(ILogger<Worker> logger, IServiceScopeFactory serviceScopeFactory)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory));
        }
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                // We ultimately resolve the actual services we use from the scope we create below.
                // This ensures that all services that were registered with services.AddScoped<T>()
                // will be disposed at the end of the service scope (the current iteration).
                using var scope = _serviceScopeFactory.CreateScope();

                var configuration = scope.ServiceProvider.GetRequiredService<IWorkFlowScheduleService>();
                configuration.DailySchedule(dateTime: DateTime.Now);

                _logger.LogInformation($"Sending message to ");

                await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
            }
        }
    }

【问题讨论】:

  • 不要——让它成为一个标准的控制台应用程序并通过你的平台调度程序运行它(例如 Linux 的 crontab)。较低的复杂性将是您以后感谢自己的事情。
  • 你打算在什么操作系统上安排这个?
  • 也许这对你有帮助? stackoverflow.com/questions/58535975/…
  • @Clint 我在 Windows 上运行它
  • 为什么不在 Windows 任务计划程序上安排它,并安排在特定的 DateTime x 间隔执行?

标签: c# .net asp.net-core


【解决方案1】:

这是我的解决方案。

 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     do
     {
         int hourSpan = 24 - DateTime.Now.Hour;
         int numberOfHours = hourSpan;

         if (hourSpan == 24)
         {
             //do something
             numberOfHours = 24;
         }

         await Task.Delay(TimeSpan.FromHours(numberOfHours), stoppingToken);
     }
     while (!stoppingToken.IsCancellationRequested);
 }

【讨论】:

    【解决方案2】:

    输入一个等到午夜的初始Task.Delay 怎么样,做你需要做的任何事情,然后Task.Delay 24 小时?

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // calculate seconds till midnight
        var now = DateTime.Now;
        var hours = 23 - now.Hour;
        var minutes = 59 - now.Minute;
        var seconds = 59 - now.Second;
        var secondsTillMidnight = hours * 3600 + minutes * 60 + seconds;
    
        // wait till midnight
        await Task.Delay(TimeSpan.FromSeconds(secondsTillMidnight), stoppingToken);
    
        while (!stoppingToken.IsCancellationRequested)
        {
            // do stuff
            _logger.LogInformation($"Sending message to ");
    
            // wait 24 hours
            await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以将 Quartz.NET 库用于后台服务。

      【讨论】:

      • 提供一些上下文,因为如果它只是命名一个没有任何上下文(或示例)的库,这不是一个好的答案
      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 2012-08-09
      • 2014-12-06
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      相关资源
      最近更新 更多