Updated on
PeriodicTimer is a .NET timer that we await instead of handing it a callback. We call WaitForNextTickAsync() in a loop, do our work on each tick, and the loop ends when we cancel a token or dispose of the timer.
We need this kind of loop whenever a task has to run at regular intervals, such as refreshing data or updating a user interface. PeriodicTimer arrived in .NET 6, and .NET 8 added a settable Period and a constructor that takes a TimeProvider, which lets us test timer code without waiting on the real clock.
Let’s begin!
How Does the PeriodicTimer Class Work in C#?
PeriodicTimer lives in System.Threading and wraps a single timer that ticks once every period. Each tick is recorded inside the timer, and we collect it with await timer.WaitForNextTickAsync().
That call returns a ValueTask<bool>. It completes with true when the timer ticks and with false once someone disposes of the timer. If we pass a CancellationToken and cancel it, the wait throws an OperationCanceledException instead.
So the whole pattern is a while loop around that call, with our work as the loop body. Our code only runs between two waits, so two ticks of the same timer never run the body at the same time.
There are two ways to stop the loop. Cancelling the token ends the current wait with an exception, which suits shutdown that already flows through a token. Disposing of the timer ends the loop quietly through the false result.
If ValueTask is new to us, our article on ValueTask explains how it differs from Task.
In our example, we wrap that loop in a small class.
First, let’s define some variables, which we are going to use with our example:
private readonly PeriodicTimer _periodicTimer; private readonly CancellationTokenSource _cancellationToken = new(); private Task? _task; private int _size;
Here, we define a PeriodicTimer variable, which we will instantiate later. Also, we define and initialize a CancellationTokenSource variable, which comes in handy when defining the logic we are going to use to terminate a recurring nullable Task. Finally, since we want to create arrays of random numbers, the _size variable holds the number of elements we want to create. Â
Second, let’s create a constructor to initialize our _periodicTimer and the _size of the arrays we want to create:
public PeriodicTimerMethods(TimeSpan timeSpan, int size)
{
_periodicTimer = new PeriodicTimer(timeSpan);
_size = size;
}
Next, let’s create a function to carry out a task, such as creating a random array of integers, which we need to time:
public static int[] CreateRandomArray(int size)
{
var array = new int[size];
for (int i = 0; i < size; i++)
{
array[i] = Random.Shared.Next();
}
return array;
}
The method returns an array of random integers of a given size.Â
After that, let’s implement a method that invokes CreateRandomArray() and a PeriodicTimer instance:
private async Task RandomArrayTimerAsync()
{
try
{
var stopWatch = System.Diagnostics.Stopwatch.StartNew();
var numberOfArrays = 1;
while (await _periodicTimer.WaitForNextTickAsync(_cancellationToken.Token))
{
var array = CreateRandomArray(_size);
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine($"Created {numberOfArrays++} arrays in {stopWatch.Elapsed.TotalSeconds:F1}s");
Console.WriteLine(DateTime.Now.ToString("O"));
}
}
catch(OperationCanceledException)
{
}
}
Here, we want to check how many CreateRandomArray() instances we can create and display before the user cancels the task. The WaitForNextTickAsync() method waits for the next tick of the timer or for the timer to be terminated. Also, we define a Stopwatch instance to track how much time has passed since the loop started.Â
Next, let’s create two helper methods to initiate and terminate the task:
public void Start()
{
_task = RandomArrayTimerAsync();
}
public async Task StopTaskAsync()
{
if (_task is null)
{
return;
}
_cancellationToken.Cancel();
await _task;
_cancellationToken.Dispose();
_periodicTimer.Dispose();
Console.WriteLine("The array task was canceled");
}
In the StopTaskAsync() method, we invoke the Cancel() method, which in turn sets the IsCancellationRequested property to true. We also allow any pending tasks to be completed before disposing of the object to free up resources. Finally, we dispose of the timer itself, which stops it ticking. PeriodicTimer implements IDisposable, and a timer we never dispose keeps firing in the background until the garbage collector finds it.
In the main program, we can verify that our solution works as it should:
Console.WriteLine("Enter array size");
var numOfElements = Convert.ToInt32(Console.ReadLine());
var timerTask = new PeriodicTimerMethods(TimeSpan.FromSeconds(1), numOfElements);
timerTask.Start();
Console.WriteLine("Press any key to stop the task");
Console.ReadKey();
await timerTask.StopTaskAsync();
Finally, let’s see the program’s output when we execute it:
Enter array size 5 Press any key to stop the task 74860115 403844982 1568335947 1650255327 473679582 Created 1 arrays in 1.0s 2026-11-01T17:36:10.1960004+01:00 563735956 241122553 1705606789 1691679470 1014848227 Created 2 arrays in 2.0s 2026-11-01T17:36:11.1917343+01:00 670291860 1519330754 1493778324 724968363 1961999910 Created 3 arrays in 3.0s 2026-11-01T17:36:12.1925498+01:00 The array task was canceled
We can see that we can create random arrays and output them while displaying the elapsed time. The timestamps land about one second apart, even though each tick also prints to the console.
Why Use the PeriodicTimer in C#?
To start with, it’s pretty simple to implement. There’s no event to subscribe to and no callback to make thread-safe, and the loop reads top to bottom like any other async method.
The second reason is steady timing. PeriodicTimer is no more accurate than System.Threading.Timer, because it runs on the same runtime timer queue. Its advantage is that our work doesn’t move the schedule. The timer keeps ticking every period on its own, so a loop body that takes 300 milliseconds doesn’t delay every later tick by 300 milliseconds. A loop built on await Task.Delay(period) does, because each delay only starts after the work ends.
Finally, it fits places where cancellation is critical. WaitForNextTickAsync() accepts a CancellationToken, so the loop stops as soon as the host shuts down or conditions change, without a flag of our own to check.
We compare await Task.Delay() with Thread.Sleep() in a separate article.
How Do We Change the Period or Test a PeriodicTimer?
.NET 8 added two members that the original .NET 6 class didn’t have.
The first is a settable Period property. When we assign a new TimeSpan, the timer reschedules from that moment, and a tick that is already waiting to be consumed stays where it is. That lets a loop slow down or speed up, for example backing off while an API returns errors, without disposing of the timer and creating a new one.
The second is a constructor that takes a TimeProvider. In production, we use the plain constructor and the timer runs on the system clock. In a test, we pass a FakeTimeProvider from the Microsoft.Extensions.TimeProvider.Testing package and move time forward ourselves with Advance().
Why does that matter? A timer test on the real clock has to wait. Our original test waits five real seconds. With a fake clock, a test that covers minutes of timer behaviour finishes in milliseconds and gives the same result on a slow build server as on our machine.
Let’s change the period of a timer that runs on a fake clock and check when it ticks:
using Microsoft.Extensions.Time.Testing;
[TestMethod]
public void GivenANewPeriod_WhenTimePasses_ThenTheTimerTicksOnTheNewSchedule()
{
var time = new FakeTimeProvider();
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), time);
timer.Period = TimeSpan.FromSeconds(5);
var tick = timer.WaitForNextTickAsync();
time.Advance(TimeSpan.FromSeconds(4));
Assert.IsFalse(tick.IsCompleted);
time.Advance(TimeSpan.FromSeconds(1));
Assert.IsTrue(tick.IsCompleted);
}
We create the timer with a one-second period, then switch it to five seconds before any time passes. After four fake seconds, the wait still hasn’t completed, so the old one-second schedule is gone. One more second and the tick arrives. The test doesn’t wait at all, because Advance() fires the fake timer synchronously.
We cover fake clocks in more depth in our article on testing time-dependent code with TimeProvider.
What Happens When the Work Takes Longer Than the Period?
The timer keeps ticking while our loop body runs, but it doesn’t queue the ticks up. Microsoft’s API reference for WaitForNextTickAsync() puts it plainly: “multiple ticks are coalesced into a single tick if they occur between calls” to the method.
Let’s say the period is one second and one pass of the body takes 3.5 seconds. Three ticks fire in the meantime. When the body finishes, the next wait completes at once, because one tick is waiting for us. The other two are gone, and the wait after that completes at the four-second mark, on the original schedule.
As a result, the body never runs twice at the same time, and a slow pass never sets off a burst of catch-up runs.
There’s one rule we must not break in return: only one WaitForNextTickAsync() call may be in flight at a time. A second call while the first is pending throws an InvalidOperationException, so two loops can’t share one timer.

Ticks that fire while the loop body runs collapse into one, and the next tick lands on the original schedule.
We can prove both behaviours with a fake clock. First, the missed ticks:
[TestMethod]
public async Task GivenMissedTicks_WhenWeWaitAgain_ThenTheyCollapseIntoOne()
{
var time = new FakeTimeProvider();
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), time);
time.Advance(TimeSpan.FromSeconds(3.5));
Assert.IsTrue(await timer.WaitForNextTickAsync());
var nextTick = timer.WaitForNextTickAsync();
Assert.IsFalse(nextTick.IsCompleted);
time.Advance(TimeSpan.FromSeconds(0.5));
Assert.IsTrue(await nextTick);
}
Here, Advance() plays the role of our slow loop body. It moves the clock 3.5 seconds past three tick times while nobody is waiting. The first wait completes immediately with the one stored tick. The second wait doesn’t complete, so the other two ticks are gone. Half a second later, at the four-second mark, it completes on schedule.
Now let’s break the single-consumer rule on purpose:
[TestMethod]
public void GivenAWaitInFlight_WhenWeWaitTwice_ThenTheSecondCallThrows()
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
_ = timer.WaitForNextTickAsync();
Assert.ThrowsExactly<InvalidOperationException>(() => timer.WaitForNextTickAsync());
}
The first wait is still pending when we ask for a second one, and the timer refuses it. If two pieces of work need their own schedule, each one gets its own PeriodicTimer.
Other Timers in C#
Besides the PeriodicTimer class, other timer classes are also available in .NET. System.Timers.Timer class is event-based, generating an event after a set interval and providing options for creating recurring events. This class is ideal for creating server-based or service components that we intend to consume in multithreaded applications. Besides, the class has no user interface and is never visible at runtime.Â
Another timer in .NET is System.Threading.Timer, which works by executing a single callback on a thread pool at regular intervals. We can’t swap the callback once the timer exists, although its Change() method lets us adjust the due time and the interval. Just like the System.Timers.Timer class, System.Threading.Timer is also ideal for server-based or service components in multithreaded applications. It doesn’t have a user interface and is never visible at runtime.
The System.Windows.Forms.Timer class is present in Windows Forms applications and fires events at regular intervals. Unlike the first two classes, this class is ideal for single-threaded environments. Finally, on the old ASP.NET Web Forms stack, which runs on .NET Framework only, the System.Web.UI.Timer control initiates asynchronous or synchronous postbacks at set intervals.Â
PeriodicTimer has built-in support for cancellation. It also doesn’t rely on callbacks, so ticks can’t overlap and there’s no reentrancy to guard against. That makes it the natural pick for an async loop that runs one job at a time. When we need a callback on a thread pool thread or several handlers on one timer, System.Threading.Timer and System.Timers.Timer are still the right tools.
Conclusion
In this article, we’ve learned how to use the PeriodicTimer class in C#. Its simplicity, its steady schedule and its cancellation support make it a good fit for work that repeats. We’ve also seen what happens to ticks that fire while our loop is busy, and how .NET 8 lets us change the period and test the timer on a fake clock.
If the loop runs inside an ASP.NET Core app, our guide to recurring background tasks in ASP.NET Core shows where it fits in a BackgroundService.
Have you implemented the PeriodicTimer class in your applications? Let us know in the comments section below.
Tested with .NET 10.0.10, MSTest 4.5.2 and Microsoft.Extensions.TimeProvider.Testing 10.11.0.
