.Net 6 Periodic Timer (async)

Adil Ansari
2 min readFeb 10, 2023

--

Introduction

.Net provides lots of types of Timer classes that you, as a developer, probably have come across in your day-to-day work. Below is the list:

  1. System.Web.UI.Timer
  2. System.Windows.Forms.Timer
  3. System.Timers.Timer
  4. System.Threading.Timer
  5. System.Windows.Threading.DispatcherTimer

.NET 6 introduces one more timer class, called PeriodicTimer. It doesn’t rely on callbacks and instead waits asynchronously for timer ticks. So, if you don’t want to use the callbacks as it has their own flaws PeriodicTimer is a good alternative.

You can create the new PeriodicTimer instance by passing the one argument, Period, the time interval in milliseconds between invocations.

 // create a new instance of PeriodicTimer which ticks after 1 second interval
PeriodicTimer secondTimer = new PeriodicTimer(new TimeSpan(0, 0, 1));

How to use Periodic Timer

You can call the WaitForNextTickAsync method in an infinite for or while loop to wait asynchronously between ticks.

while (await secondTimer.WaitForNextTickAsync())
{
// add your async business logic here
}

Example

Let’s write a small console application with two methods having their own PeridicTimer instances, one is configured to tick every minute, and another one ticks every second.

With every tick, increase the counter by one and print it in the console.

static async Task SecondTicker()
{
PeriodicTimer secondTimer = new PeriodicTimer(new TimeSpan(0, 0, 1));

while (await secondTimer.WaitForNextTickAsync())
{
secs++;
Console.SetCursorPosition(0, 0);
Console.Write($"secs: {secs.ToString("00")}");
}
}

another one, which sets the second counter to 0 as every minute elapses.

static async Task MinuteTicker()
{
PeriodicTimer minuteTimer = new PeriodicTimer(new TimeSpan(0, 1, 0));

while (await minuteTimer.WaitForNextTickAsync())
{
mins++;
secs = 0;
Console.SetCursorPosition(0, 1);
Console.Write($"mins: {mins.ToString("00")}");
}
}

Now let’s run them in parallel

static int secs = 0, mins = 0;
static async Task Main(string[] args)
{
Console.WriteLine("secs: 00");
Console.WriteLine("mins: 00");

var secondTicks = SecondTicker();
var minuteTicks = MinuteTicker();
await Task.WhenAll(secondTicks, minuteTicks);
}

Output:

Here is the output that you get when you run the code

Take away

--

--

Adil Ansari
Adil Ansari

Written by Adil Ansari

Experienced C#, .Net, Office 365, and Azure Developer with around 15 years of experience in designing and implementing the maintainable software

No responses yet