后台任務如何支持間隔時間、Cron表達式兩種方式?
分享一個項目TaskScheduler,這是我從Furion項目中拷出來的
開始
間隔時間后台服務
public class IntervalBackgroundService : BackgroundService
{
private readonly ILogger<IntervalBackgroundService> _logger = null;
public IntervalBackgroundService(ILogger<IntervalBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await SpareTime.DoAsync(1000, () =>
{
_logger.LogInformation("Interval Worker running at: {time}", DateTimeOffset.Now);
}, stoppingToken);
}
}
}
Cron表達式后台服務
public class CronBackgroundService : BackgroundService
{
private readonly ILogger<CronBackgroundService> _logger = null;
public CronBackgroundService(ILogger<CronBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// 執行 Cron 表達式任務
await SpareTime.DoAsync("*/5 * * * * *", () =>
{
_logger.LogInformation("Cron Worker running at: {time}", DateTimeOffset.Now);
}, stoppingToken, CronFormat.IncludeSeconds);
}
}
}
