我希望每晚都能运行一个后台服务。.NET Core默认的BackgroundService在task.delay上运行,我希望每天在午夜运行(24小时间隔)。
问题在于BackgroundService会在每个task.Delay间隔上运行,而不是指定的特定时间。
问题在于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);
}
}
}