public class PeriodicBackgroundTask : BackgroundService { private readonly TimeSpan _period = TimeSpan.FromSeconds(5); private readonly ILogger<PeriodicBackgroundTask> _logger; public PeriodicBackgroundTask(ILogger<PeriodicBackgroundTask> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using PeriodicTimer timer = new PeriodicTimer(_period); while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) { _logger.LogInformation("Executing PeriodicBackgroundTask"); System.Console.WriteLine("Executing PeriodicBackgroundTask"); } } }
用到了.Net6新定时器PeriodicTimer,可以更方便的处理异步。
标签:core,PeriodicBackgroundTask,TimeSpan,stoppingToken,BackgroundService,PeriodicTim From: https://www.cnblogs.com/Insist-Y/p/17437857.html