Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 182 ยท Async and Concurrency

Timers: PeriodicTimer and System.Threading.Timer

Run recurring work in C# with PeriodicTimer, System.Threading.Timer and Task.Delay loops. Learn which to choose, how to stop cleanly and how to avoid overlapping ticks.

Plenty of programs need to do something again and again: refresh a cache every minute, send a heartbeat every five seconds, poll a queue, flush a log buffer, or draw an animation frame. .NET has several timer classes for this, and picking the wrong one leads to classic bugs such as overlapping runs, leaked timers and callbacks that keep running after the object is gone.

This lesson covers the two timers you should reach for in modern code, PeriodicTimer and System.Threading.Timer, shows the simple Task.Delay loop, and explains the others you will meet in older code. It builds on async and await, cancellation and threads.

Which timer should I use?

flowchart TD
    A["I need recurring work"] --> B{"Is the work async,<br/>inside an async method?"}
    B -->|"yes"| C["PeriodicTimer"]
    B -->|"no, a plain callback"| D["System.Threading.Timer"]
    A --> E{"UI app with a UI thread?"}
    E -->|"yes"| F["The UI framework timer<br/>(DispatcherTimer, WinForms Timer)"]

For most new server and console code, PeriodicTimer is the first choice.

Timer Style Best for
PeriodicTimer await timer.WaitForNextTickAsync() in a loop Background loops in async code
System.Threading.Timer Callback on a thread-pool thread Simple fire-and-forget callbacks
Task.Delay in a loop await Task.Delay(...) Quick scripts where drift does not matter
System.Timers.Timer Event Elapsed Older code; a wrapper around the thread-pool timer
UI timers Event on the UI thread Updating controls in desktop apps

PeriodicTimer

PeriodicTimer (in System.Threading, since .NET 6) is designed for async loops. You create it with an interval, then repeatedly await WaitForNextTickAsync. The method returns true when a tick arrives and false when the timer has been disposed. You pass a CancellationToken to stop waiting early; in that case it throws OperationCanceledException.

C# A PeriodicTimer loop

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.

The big advantage over a callback timer is that ticks cannot overlap. The next tick is not delivered until you call WaitForNextTickAsync again, so your loop body always finishes before the next iteration begins. If the body takes longer than the interval, the timer does not queue up a pile of ticks. It remembers at most one missed tick and the next wait returns immediately, then the rhythm continues.

C# Slow work never overlaps

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.

Stopping a PeriodicTimer cleanly

In a long-running background service you stop the loop with a cancellation token. Catch the OperationCanceledException outside the loop so the shutdown is quiet.

C# Stopping with a token

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.

You can also change the interval at runtime by setting timer.Period. And be aware of one rule: a single PeriodicTimer supports only one consumer at a time. Do not call WaitForNextTickAsync from two tasks at once.

In a hosted service (see the generic host) the same loop goes inside ExecuteAsync, with stoppingToken as the token.

System.Threading.Timer

System.Threading.Timer calls a method for you on a thread-pool thread. You give it a callback, a state object, a delay before the first call (dueTime) and an interval (period). It starts immediately.

C# A callback timer

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.

The callback runs on a pool thread, not on the thread that created the timer, so any shared state must be protected (here Interlocked is used, see synchronization). Important behaviors to remember:

  • Callbacks can overlap. If one callback runs longer than the period, the timer starts the next one on another thread. Two callbacks may run at the same time.
  • Exceptions in a callback crash the process. Nobody awaits the callback, so an unhandled exception is fatal. Wrap the body in try/catch.
  • The timer can be garbage collected. Keep a reference to the Timer in a field for as long as it should run. If you only keep it in a local variable that is no longer used, the GC may collect it and the ticks quietly stop.
  • Stop with Change(Timeout.Infinite, Timeout.Infinite) or dispose it. Use await timer.DisposeAsync() to also wait for a running callback to finish.

Avoiding overlap with a one-shot timer

A common trick is to make the timer fire once (period = Timeout.Infinite) and re-arm it at the end of every callback. This guarantees that runs never overlap, and the delay is measured from the end of the previous run.

C# Re-arming a one-shot timer

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.

A Task.Delay loop

The simplest "timer" of all is a loop with await Task.Delay. It is perfect for scripts and small background jobs:

C#
while (!token.IsCancellationRequested)
{
    await DoWorkAsync();
    await Task.Delay(TimeSpan.FromSeconds(5), token);
}

The difference from PeriodicTimer is that the delay starts after the work ends, so the interval is "work time + delay" and slowly drifts. With PeriodicTimer the ticks stay on a fixed schedule (when the work is shorter than the interval). Choose the delay loop when you want a pause between runs, and PeriodicTimer when you want a steady rhythm. For a closer look at the delay and cancellation behavior see the cancellation lesson.

Older timers

  • System.Timers.Timer raises an Elapsed event on the thread pool. It is basically a wrapper around the callback timer, swallows exceptions thrown from the handler (which hides bugs), and implements IDisposable. It is fine in legacy code but there is no reason to choose it for new projects.
  • UI timers such as WPF's DispatcherTimer or WinForms' Timer tick on the UI thread so you can touch controls directly. Do slow work on another thread, because the UI freezes while the tick handler runs.
  • Clock accuracy. Timers are not real-time clocks. A 10 ms interval can fire 15 ms apart on a busy machine. Measure time with Stopwatch or TimeProvider.GetTimestamp, never by counting ticks.

Testing timer code

Code that waits for real time makes tests slow and flaky. .NET 8 introduced TimeProvider, an abstraction for the clock. TimeProvider.CreateTimer and new PeriodicTimer(period, timeProvider) let a test use a fake time provider and advance time manually. Design your classes to accept a TimeProvider through dependency injection; in production you pass TimeProvider.System.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does WaitForNextTickAsync return when the PeriodicTimer has been disposed?

    The method returns true for a tick and false after Dispose, so while (await timer.WaitForNextTickAsync()) ends naturally when the timer is disposed.
  2. 2. Which timer can run two callbacks at the same time if a callback is slower than the period?

    System.Threading.Timer starts every callback on a pool thread regardless of whether the previous one finished. PeriodicTimer and delay loops run one iteration after another.
  3. 3. Why should you keep a System.Threading.Timer in a field?

    Nothing but your reference keeps the timer alive. Once the GC sees no more references, it can collect the timer and the callbacks stop.
  4. 4. What is a key difference between a Task.Delay loop and PeriodicTimer?

    With Task.Delay the total period is work time plus delay. PeriodicTimer ticks on a steady schedule independent of how long each iteration took, as long as the work fits in the interval.

Summary

  • Use PeriodicTimer with await timer.WaitForNextTickAsync(token) for recurring async work: ticks never overlap and cancellation is easy.
  • System.Threading.Timer runs a callback on the pool; guard shared state, catch exceptions, keep a reference and expect possible overlap.
  • Re-arm a one-shot Timer at the end of the callback when runs must never overlap.
  • A Task.Delay loop is simple but drifts, because the delay comes after the work.
  • Prefer PeriodicTimer over System.Timers.Timer in new code and use TimeProvider to make timers testable.

Next lesson: garbage collection.