我想每天半夜运行一次后台服务。 .NET Core默认BackgroundService在task.delay
上运行,我想每隔半夜(24小时间隔)运行一次。
我有BackgroundService的问题在每个task.Delay
间隔而不是指定的特定时间运行。
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);
}
}
}
答案 0 :(得分:6)
这是我的解决方法。
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);
}
答案 1 :(得分:0)
加入一个等待到午夜的初始 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);
}
}
答案 2 :(得分:-2)
您可以将Quartz.NET库用于后台服务。