实现示例如下:
public class TimedHealthCheckService : TimerScheduledService{ public TimedHealthCheckService(ILogger<TimedHealthCheckService> logger) : base(TimeSpan.FromSeconds(5), logger) { } protected override Task ExecuteInternal(CancellationToken stoppingToken) { Logger.LogInformation("Executing..."); return Task.CompletedTask; }}运行输出如下:

文章插图
More
新的 PeriodicTimer 相比之前的几个 Timer 来说 , 有下面几个特点
- 没有 callback 来绑定事件
- 不会发生重入 , 只允许有一个消费者 , 不允许同一个 PeriodicTimer 在不同的地方同时 WaitForNextTickAsync , 不需要自己做排他锁来实现不能重入
- 异步化 , 之前的几个 timer 的 callback 都是同步的 , 使用新的 timer 我们可以更好的使用异步方法 , 避免写 Sync over Async 之类的代码
- Dispose() 之后 , 该实例就无法再使用 , WaitForNextTickAsync 始终返回 false
using var cts = new CancellationTokenSource();cts.CancelAfter(TimeSpan.FromSeconds(30));using var timer = new PeriodicTimer(TimeSpan.FromSeconds(3));try{ while (await timer.WaitForNextTickAsync(cts.Token)) { await Task.Delay(5000); Console.WriteLine($"Timed event triggered({DateTime.Now:HH:mm:ss})"); }}catch (OperationCanceledException){ Console.WriteLine("Operation cancelled");}猜一下输出结果是什么 , Timed event triggered 会输出几次
文章插图
References
- https://www.ilkayilknur.com/a-new-modern-timer-api-in-dotnet-6-periodictimer
- https://docs.microsoft.com/en-us/dotnet/api/system.threading.periodictimer?view=net-6.0
- https://github.com/dotnet/runtime/blob/v6.0.0/src/libraries/System.Private.CoreLib/src/System/Threading/PeriodicTimer.cs
- https://github.com/dotnet/runtime/issues/31525
- https://github.com/WeihanLi/SamplesInPractice/blob/master/net6sample/PeriodicTimerSample/Program.cs
- https://github.com/OpenReservation/ReservationServer/blob/dev/OpenReservation.Helper/Services/CronScheduleServiceBase.cs#L91
推荐阅读
- 2021年男工人退休年龄最新规定是什么?
- 哪种桔子皮做陈皮最好,新鲜桔子皮怎么做陈皮
- 信阳毛尖的特点,女性喝信阳毛尖的好处
- 头围的测量方法
- 发型|五一发型别乱剪,新女发18款送给大家,想不美都难
- 新生儿黄疸可以喝水吗
- 如何判断新生儿不舒服
- 新生儿黄疸最晚多久退
- 新生儿吃奶老是吐奶怎么回事
- .net6给winform带来的新功能
