C# Reference ยท Date, Time and Globalization
The PeriodicTimer class
Reference for System.Threading.PeriodicTimer in C#: await repeating ticks in an async loop, stop with a CancellationToken, and avoid overlapping callbacks.
PeriodicTimer is a timer designed for async code. Instead of calling a callback, it lets you await timer.WaitForNextTickAsync() in a loop. Each call completes when the next period has elapsed. Because the loop body runs between ticks, work never overlaps with itself, and exceptions flow through normal try/catch.
It was added in .NET 6. Compared with System.Threading.Timer and System.Timers.Timer, it needs no callback synchronization, and it is safe against a callback that takes longer than the period: ticks do not queue up. If you are late, one tick is available immediately and extra missed ticks are dropped.
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)); while (await timer.WaitForNextTickAsync()) { Console.WriteLine("tick"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public sealed class PeriodicTimer : IDisposable { public PeriodicTimer(TimeSpan period); public PeriodicTimer(TimeSpan period, TimeProvider timeProvider); public TimeSpan Period { get; set; } public ValueTask<bool> WaitForNextTickAsync(CancellationToken cancellationToken = default); public void Dispose(); }
| Parameter / member | Description |
|---|---|
period |
Time between ticks. Must be greater than zero and at most about 49 days (uint.MaxValue - 1 ms). |
timeProvider |
Source of time for scheduling; lets tests control ticks (see TimeProvider). |
WaitForNextTickAsync |
Completes with true at the next tick, or false after Dispose. |
cancellationToken |
Cancels the wait with OperationCanceledException. |
Errors: the constructor and the Period setter throw ArgumentOutOfRangeException for invalid periods. Only one WaitForNextTickAsync call may be pending at a time; calling it again while a previous wait is still pending throws InvalidOperationException ("Operation is not valid due to the current state of the object."), so use one consumer per timer.
Usage notes
- One consumer. A
PeriodicTimeris meant to be awaited by a single loop. Do not callWaitForNextTickAsyncfrom several tasks at once. - The first tick comes after one period, not immediately. If you want to run once at start, call your work method before the loop.
- Slow work does not stack ticks. If the loop body takes longer than the period, the timer does not queue missed ticks: at most one is pending. The loop simply runs back to back.
- Stop it with a token or
Dispose. Disposing makes the next wait returnfalse, which ends awhileloop cleanly; cancellation throwsOperationCanceledException, which hosted services usually catch at the top. - No drift on the schedule. Ticks are scheduled from the start of the timer, not from the end of the body, so the average rate stays at one per period.
- Use it in background services. A
BackgroundService.ExecuteAsyncwith aPeriodicTimerloop is the standard pattern for periodic jobs (cleanup, polling). - Not for UI thread callbacks. It does not marshal to a UI thread; resume continues with the normal synchronization context rules for
await. - For one-off delays use
Task.Delay. For many timers with callbacks useTimeProvider.CreateTimerorSystem.Threading.Timer.
Related
- TimeProvider
- TimeSpan in depth
- Reference: async and await
- Tutorial: Dates and times