Microsoft在Implement background tasks in microservices with IHostedService and the BackgroundService class处永久/连续IHostedService的示例使用while + Task.Delay'模式'。
这用一个简化的代码片段在下面显示。

public class GracePeriodManagerService : BackgroundService

(...)

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        //Do work

        await Task.Delay(timeSpan, stoppingToken);
    }
}


这种模式经历了缓慢的变化-每个timeSpan + how_long_work_took都会完成工作。即使how_long_work_took在一段时间内非常小,它也会加起来。

我想避免根据timeSpan花费的时间来计算work

一个健壮的解决方案是每运行一次fixed_amount_of_time?

大声考虑:如果我使用诸如HangFire之类的任务计划程序库,在ExecuteAsync内使用IHostedService / BackgroundService是否有意义?

奖励是能够在某个时间点(例如午夜)运行任务

最佳答案

这就是我处理此类问题的方式...就我而言,我需要在特定的日期,特定的时间启动服务,并每隔x天重复一次。但是我不知道这到底是不是你在寻找什么:)

public class ScheduleHostedService: BackgroundService
{
    private readonly ILogger<ScheduleHostedService> _logger;
    private readonly DaemonSettings _settings;

    public ScheduleHostedService(IOptions<DaemonSettings> settings, ILogger<ScheduleHostedService> logger)
    {
        _logger = logger;
        _settings = settings.Value;
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        DateTime? callTime=null;
        if (_settings.StartAt.HasValue)
        {

            DateTime next = DateTime.Today;
            next = next.AddHours(_settings.StartAt.Value.Hour)
                .AddMinutes(_settings.StartAt.Value.Minute)
                .AddSeconds(_settings.StartAt.Value.Second);
            if (next < DateTime.Now)
            {
                next = next.AddDays(1);
            }

            callTime = next;
        }

        if (_settings.StartDay.HasValue)
        {
            callTime = callTime ?? DateTime.Now;
            callTime = callTime.Value.AddDays(-callTime.Value.Day).AddDays(_settings.StartDay.Value);
            if (callTime < DateTime.Now)
                callTime = callTime.Value.AddMonths(1);
        }
        if(callTime.HasValue)
            await Delay(callTime.Value - DateTime.Now, stoppingToken);
        else
        {
            callTime = DateTime.Now;
        }
        while (!stoppingToken.IsCancellationRequested)
        {
            //do smth
            var nextRun = callTime.Value.Add(_settings.RepeatEvery) - DateTime.Now;

            await Delay(nextRun, stoppingToken);
        }
    }
    static async Task Delay(TimeSpan wait, CancellationToken cancellationToken)
    {
        var maxDelay = TimeSpan.FromMilliseconds(int.MaxValue);
        while (wait > TimeSpan.Zero)
        {
            if (cancellationToken.IsCancellationRequested)
                break;
            var currentDelay = wait > maxDelay ? maxDelay : wait;
            await Task.Delay(currentDelay, cancellationToken);
            wait = wait.Subtract(currentDelay);
        }
    }
}


我编写了Delay函数来处理超过28天的延迟。

08-06 18:46