我有一個派生自IHostedService. 在這里,我有StartAsync如下所示的覆寫方法:
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoSomething, null, offset, TimeSpan.FromHours(1));
return Task.CompletedTask;
}
在這里,我有 TimeSpan 類的變數偏移量。
我需要的:
我需要以這樣的方式計算偏移量,即任務“DoSomething”將在每小時開始時執行,例如:10:00、13:00、21:00 或 00:00。所以這個偏移量需要以分鐘為單位。
示例:假設應用程式在 開始運行13:48PM,正確的偏移量為 12 分鐘,下一小時為14。
我的問題: 我將如何計算以分鐘為單位的偏移量,直到下一小時?
uj5u.com熱心網友回復:
就像是
var minutes = (DateTime.Today.AddHours(DateTime.Now.Hour 1)-DateTime.Now).TotalMinutes
應該做的伎倆
uj5u.com熱心網友回復:
我的回答是:
TimeSpan offset = TimeSpan.FromMinutes(60 - DateTimeOffset.UtcNow.Minute);
但是有沒有其他(更好的)方法來實作這個?
uj5u.com熱心網友回復:
在 Microsoft檔案中,有TimedHostedService類的官方版本
您可以使用 cron 決議 nuget pacakge ( NCronTab.signed ) 根據配置計算時間,它將成為一個漂亮的解決方案
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger<TimedHostedService> _logger;
private Timer _timer;
private readonly CrontabSchedule _cronSchedule;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
_cronSchedule = CrontabSchedule.Parse("0 * * * *");
}
public Task StartAsync(CancellationToken stoppingToken)
{
var now = DateTime.Now;
var nextOccurance = _cronSchedule.GetNextOccurrence(now);
_logger.LogInformation("Configuring next run at: {time}", nextOccurance);
await Task.Delay(nextOccurance - now, stoppingToken);
DoWork()
return Task.CompletedTask;
}
private void DoWork()
{
_logger.LogInformation(
"Timed Hosted Service is working. Count: {Count}", count);
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348138.html
上一篇:c#中的foreach問題
