2 回答
TA贡献1864条经验 获得超6个赞
这就是我处理此类事情的方式......在我的情况下,我需要在特定日期、特定时间启动服务并每隔 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 天的延迟。
TA贡献1840条经验 获得超5个赞
您可以考虑使用 .NET 的 Reactive 扩展,并将其实现为带有 Timer和Cancellation Token. 使用 aScheduler您可以确定最佳线程方法(请参阅此处)
下面的代码片段可用于ExecuteAsync显示任意 3 秒启动时间然后具有 60 秒到期日期的方法(可以是任何时间长度。注意Timestamp()它允许使用整数传递本地时间。
CancellationToken cancellationToken = CancellationToken.None;
Observable
.Timer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(60))
.Timestamp()
.ObserveOn(NewThreadScheduler.Default)
.Subscribe(
x =>
{
// do some task
} ,
cancellationToken);
- 2 回答
- 0 关注
- 300 浏览
添加回答
举报