![](/img/trans.png)
[英]How to run multiple BackgroundService parallel in .net core 3.0?
[英]Run BackgroundService every day at midnight in .Net Core 3.0
我想每天午夜運行后台服務。 .NET 核心默認 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);
}
}
}
這是我的解決方案。
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);
}
放置一個等待到午夜的初始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);
}
}
我使用 NCrontab 3.3.1
https://www.nuget.org/packages/ncrontab/
這樣,您就可以使用 cron; 否則,我會同意之前的評論之一,即創建一個控制台應用程序並將其作為 cron 或服務直接在您的服務器上運行。
下面是我如何實施 NCrontab 的示例。
public class YourServiceName : BackgroundService
{
private CrontabSchedule _schedule;
private DateTime _nextRun;
// My CrontabHelper class simply returns a string representing a cron schedule. You can just use 0 0 0 * * * to run every day at midnight instead
private string Schedule => CrontabHelper.Schedule(CrontabHelper.CronType.Day);
public YourServiceName()
{
_schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions { IncludingSeconds = true });
_nextRun = _schedule.GetNextOccurrence(DateTime.Now);
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
do
{
var now = DateTime.Now;
if (now > _nextRun)
{
// DO WORK HERE
}
await Task.Delay(5000, stoppingToken);
}
while (!stoppingToken.IsCancellationRequested);
}
}
然后在你的 program.cs 中包含這個
builder.Services.AddHostedService<YourServiceName>();
希望這可以幫助!
您可以將 Quartz.NET 庫用於后台服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.