SoFunction
Updated on 2025-03-07

Introduction to PeriodTimer in .Net 6

.net 6Added an asynchronous timerPeroidTimer, relatively ordinaryTimerThe callback, its model is simpler.

var       second = (3);
 using var timer  = new PeriodicTimer(second);

while (await ())
{
    ($"Tick {}");
}

aboutWaitForNextTickAsyncMSDN is a bit vague. In my previous code, this timer with a cycle of 3s is used as an example.

A brief test:

1. The execution time is less than the Timer cycle:

Adjust each task execution time to 2s and view the output:

    Tick 2022/1/7 11:30:58
    Tick 2022/1/7 11:31:01
    Tick 2022/1/7 11:31:04

2. The execution cycle is greater than the Timer cycle:

Adjust the execution time of each task to 5s and view the output:

    Tick 2022/1/7 11:33:08
    Tick 2022/1/7 11:33:13
    Tick 2022/1/7 11:33:18
    Tick 2022/1/7 11:33:23

From these two examples, we can summarize:

  • When the task execution time is less than the cycle, the next time triggered is the last time triggered + cycle
  • When the task execution time is greater than the cycle, it will be triggered immediately next time

This cycle strategy can be said to be very practical, and will be used laterPeriodicTimerInstead of loop callIt's

Here's the article about.Net 6In-housePeriodTimerThat’s all for the article introduced. For more related PeriodTimer content in Net 6, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!