本文介绍了IHostedService/BackgroundService 按计划运行(而不是 Task.Delay)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Microsoft 在 的微服务中的任务使用 while+Task.Delay 'pattern'.这用代码片段说明,简化版本就在下面.

Microsoft's example for a forever/continous IHostedService at Implement background tasks in microservices with IHostedService and the BackgroundService class uses while+Task.Delay 'pattern'. This illustrated with a code snippet that a simplified version is just below.

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 在一段时间内非常小,它也会加起来.

This pattern suffers from a creeping shift - the work is done every timeSpan+how_long_work_took. Even when how_long_work_took is very small over a period of time it adds up.

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

I would like to avoid calculating timeSpan based on how long work took.

在每个fixed_amount_of_time上运行的稳健解决方案是什么?.

What would a robust solution be to run every fixed_amount_of_time?.

大声思考:如果我在 ExecuteAsyncHangFire/code> 使用 IHostedService/BackgroundService 是否更有意义?

Thinking out loud: If I use a task scheduler library, like HangFire, inside ExecuteAsync does using IHostedService/BackgroundService even make sense any more?

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

A bonus would be to be able to run a task at a point in time (e.g. at midnight)

推荐答案

这就是我处理此类事情的方式...在我的情况下,我需要在特定日期、特定时间启动服务并每隔 x 天重复一次.但我不知道这是否正是您要查找的内容:)

This is how I handle such thing... In my case I need to start the service on specific day, specific hour and repeat every x days. But I don't know if it's what are you looking for exactly :)

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 天的延迟.

I wrote Delay function to handle delays longer that 28 days.

这篇关于IHostedService/BackgroundService 按计划运行(而不是 Task.Delay)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 23:04