TimeProvider and PeriodicTimer
suggest changeTwo newer APIs change how modern .NET code deals with time:
PeriodicTimerlets you write "do this every N seconds" as a plainasyncloop instead of a timer callback.TimeProvideris an abstract clock. Code that asks it for the current time, measures elapsed time, creates timers or waits withTask.Delaycan be given a fake clock in tests and run hours of simulated time in milliseconds.
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30), timeProvider);
while (await timer.WaitForNextTickAsync(cancellationToken))
{
await CheckForUpdatesAsync();
}
Versions:
- .NET 6:
PeriodicTimer - .NET 7:
Stopwatch.GetElapsedTime - .NET 8:
TimeProvider,ITimer,PeriodicTimer(period, timeProvider)and the settablePeriodicTimer.Period,TimeProvideroverloads ofTask.Delay,Task.WaitAsyncandCancellationTokenSource FakeTimeProvideris in the NuGet packageMicrosoft.Extensions.TimeProvider.Testing(10.11.0 at the time of writing)
For older code you can get TimeProvider on .NET Framework and .NET Standard 2.0 from the Microsoft.Bcl.TimeProvider package.
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs. The classic timers (System.Threading.Timer, System.Timers.Timer, UI timers) are covered in Timers and Multithreaded Timers.
PeriodicTimer: a timer you await
WaitForNextTickAsync returns a ValueTask<bool> that completes at the next tick. You call it in a loop:
using System.Diagnostics;
var sw = Stopwatch.StartNew();
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(500));
int tick = 0;
while (await timer.WaitForNextTickAsync())
{
tick++;
Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,5} ms: tick {tick}");
if (tick == 4)
break;
}
Console.WriteLine("done");
500 ms: tick 1
1000 ms: tick 2
1500 ms: tick 3
2000 ms: tick 4
done
The loop body is ordinary async code. It can await, use try/catch, keep state in local variables and return a result. There is no callback, no state object and no thread-pool thread sitting in a handler.
Ticks never overlap
The timer keeps ticking on a fixed schedule while your loop body runs. If the body is slower than the period, the missed ticks are not queued up. At most one tick is remembered, so the next WaitForNextTickAsync returns immediately, and after that the loop is back on schedule:
using System.Diagnostics;
var sw = Stopwatch.StartNew();
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(300));
for (int i = 1; i <= 4; i++)
{
await timer.WaitForNextTickAsync();
Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,5} ms: start work {i}");
if (i == 2)
await Task.Delay(1000); // slow iteration: misses ~3 ticks
}
300 ms: start work 1
600 ms: start work 2
1600 ms: start work 3
1800 ms: start work 4
Work 3 starts right after the slow iteration ends (1600 ms), and work 4 starts at the next 300 ms boundary (1800 ms), not 300 ms after work 3.
Compare with System.Threading.Timer, which calls its callback on a thread-pool thread at every period no matter whether the previous callback has finished:
using System.Diagnostics;
var sw = Stopwatch.StartNew();
int running = 0;
using var timer = new Timer(_ =>
{
int now = Interlocked.Increment(ref running);
Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,5} ms: callback on thread {Environment.CurrentManagedThreadId}, running = {now}");
Thread.Sleep(700); // work that takes longer than the period
Interlocked.Decrement(ref running);
}, null, dueTime: TimeSpan.FromMilliseconds(300), period: TimeSpan.FromMilliseconds(300));
await Task.Delay(1250);
300 ms: callback on thread 5, running = 1
600 ms: callback on thread 7, running = 2
900 ms: callback on thread 8, running = 3
1200 ms: callback on thread 9, running = 3
Three copies of the callback run at the same time. With a Timer you have to guard against that yourself (a flag, a lock, or stopping and restarting the timer from inside the callback). With PeriodicTimer overlap is impossible because there is only one loop.
PeriodicTimer also beats the older "loop with Task.Delay" pattern shown in An async cancellable polling Task that waits between iterations. await Task.Delay(period) at the end of each iteration makes the real interval period + time of the work, so the schedule drifts. PeriodicTimer ticks on a fixed schedule.
Stopping: cancellation and Dispose
There are two ways to end the loop:
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1.1));
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(400));
try
{
while (await timer.WaitForNextTickAsync(cts.Token))
{
Console.WriteLine("polling...");
}
}
catch (OperationCanceledException)
{
Console.WriteLine("cancelled");
}
// Dispose from another task: the pending wait returns false instead of throwing
var timer2 = new PeriodicTimer(TimeSpan.FromSeconds(10));
_ = Task.Run(async () => { await Task.Delay(200); timer2.Dispose(); });
bool ticked = await timer2.WaitForNextTickAsync();
Console.WriteLine($"after Dispose: {ticked}");
Console.WriteLine($"again: {await timer2.WaitForNextTickAsync()}");
polling...
polling...
cancelled
after Dispose: False
again: False
- A cancelled token makes
WaitForNextTickAsyncthrowOperationCanceledException. Disposemakes a pending (and every later)WaitForNextTickAsyncreturnfalse, sowhile (await ...)exits normally.
Rules to remember:
- Only one
WaitForNextTickAsynccall may be pending at a time. A second concurrent call throwsInvalidOperationException. The timer is meant to be driven by a single consumer loop. WaitForNextTickAsyncreturns aValueTask<bool>: await it once and don't store it.- Always dispose the timer (
using var), otherwise it keeps ticking in the background. - The first tick comes one period after the timer is created, not immediately. If you want to run the work once at startup, do it before the loop.
Changing the period
Since .NET 8 Period is settable. The new period applies from the moment you set it:
TimeProvider time = TimeProvider.System;
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100), time);
var start = time.GetTimestamp();
for (int i = 1; i <= 4; i++)
{
await timer.WaitForNextTickAsync();
Console.WriteLine($"tick {i} at {(int)time.GetElapsedTime(start).TotalMilliseconds / 100 * 100} ms");
if (i == 2)
timer.Period = TimeSpan.FromMilliseconds(500);
}
tick 1 at 100 ms
tick 2 at 200 ms
tick 3 at 700 ms
tick 4 at 1200 ms
This is handy for back-off: poll quickly while there is work, slow down when there isn't. The constructor in this example also takes a TimeProvider, which is what makes the timer testable. That's the subject of the rest of the article.
TimeProvider: an abstraction over the clock
DateTime.UtcNow, Stopwatch and Task.Delay read the real clock directly, so code that uses them can't be tested without actually waiting. System.TimeProvider (an abstract class in the base library since .NET 8) puts all of them behind one object:
| Member | Purpose |
|---|---|
GetUtcNow() |
current time as DateTimeOffset in UTC |
GetLocalNow() |
current time in LocalTimeZone |
LocalTimeZone |
time zone used by GetLocalNow |
GetTimestamp() |
high-resolution monotonic counter for measuring durations |
TimestampFrequency |
counter ticks per second |
GetElapsedTime(start) / GetElapsedTime(start, end) |
time between two timestamps |
CreateTimer(...) |
creates an ITimer |
TimeProvider.System is the real implementation:
using System.Diagnostics;
TimeProvider time = TimeProvider.System;
Console.WriteLine($"UTC now: {time.GetUtcNow():O}");
Console.WriteLine($"Local now: {time.GetLocalNow():O}");
Console.WriteLine($"Time zone: {time.LocalTimeZone.Id}");
Console.WriteLine($"Frequency: {time.TimestampFrequency:N0} ticks/s");
long start = time.GetTimestamp();
await Task.Delay(250);
TimeSpan elapsed = time.GetElapsedTime(start);
Console.WriteLine($"Elapsed: {elapsed.TotalMilliseconds:F0} ms");
// The same pair exists as static methods on Stopwatch (.NET 7+)
long t0 = Stopwatch.GetTimestamp();
await Task.Delay(100);
long t1 = Stopwatch.GetTimestamp();
Console.WriteLine($"Stopwatch: {Stopwatch.GetElapsedTime(t0).TotalMilliseconds:F0} ms");
Console.WriteLine($"Between: {Stopwatch.GetElapsedTime(t0, t1).TotalMilliseconds:F0} ms");
UTC now: 2026-10-17T23:05:06.4670228+00:00
Local now: 2026-10-18T01:05:06.4773806+02:00
Time zone: Central European Standard Time
Frequency: 10,000,000 ticks/s
Elapsed: 261 ms
Stopwatch: 106 ms
Between: 106 ms
Use timestamps, not GetUtcNow() differences, to measure durations: the wall clock can jump when the system time is adjusted, the timestamp counter can't.
Stopwatch.GetTimestamp() plus Stopwatch.GetElapsedTime(start) is the allocation-free way to time something. It replaces var sw = Stopwatch.StartNew(); ... sw.Elapsed when you only need one measurement, which matters in hot paths such as per-request timing in middleware. Stopwatch itself is covered in Stopwatches. In code you want to test, call the same methods on an injected TimeProvider instead.
Timers from a TimeProvider
CreateTimer returns an ITimer, which works like System.Threading.Timer: a callback, a state object, a due time and a period. Change reschedules it, Dispose stops it:
using System.Diagnostics;
TimeProvider time = TimeProvider.System;
var sw = Stopwatch.StartNew();
using ITimer timer = time.CreateTimer(
callback: state => Console.WriteLine($"{sw.ElapsedMilliseconds / 100 * 100,5} ms: {state}"),
state: "tick",
dueTime: TimeSpan.FromMilliseconds(200),
period: TimeSpan.FromMilliseconds(400));
await Task.Delay(1100);
timer.Change(TimeSpan.Zero, TimeSpan.FromMilliseconds(100)); // fire now, then faster
await Task.Delay(350);
timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); // pause
Console.WriteLine("paused");
await Task.Delay(500);
200 ms: tick
600 ms: tick
1000 ms: tick
1100 ms: tick
1200 ms: tick
1300 ms: tick
1400 ms: tick
paused
ITimer callbacks can overlap just like System.Threading.Timer callbacks. Prefer new PeriodicTimer(period, timeProvider) for recurring async work and use CreateTimer for one-shot timeouts or when you need a callback.
Delays and timeouts with a TimeProvider
The async helpers you already use have overloads that take a TimeProvider:
TimeProvider time = TimeProvider.System;
// Task.Delay with a provider (.NET 8+)
await Task.Delay(TimeSpan.FromMilliseconds(100), time);
Console.WriteLine("delay done");
// Timeout an operation
Task<string> slow = Task.Delay(2000).ContinueWith(_ => "result");
try
{
string r = await slow.WaitAsync(TimeSpan.FromMilliseconds(300), time);
Console.WriteLine(r);
}
catch (TimeoutException ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
// A CancellationTokenSource that cancels itself after a delay
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200), time);
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, time, cts.Token);
}
catch (TaskCanceledException)
{
Console.WriteLine("cancelled by timeout");
}
delay done
TimeoutException: The operation has timed out.
cancelled by timeout
Task.Delay(TimeSpan, TimeProvider[, CancellationToken])task.WaitAsync(TimeSpan, TimeProvider[, CancellationToken])throwsTimeoutExceptionif the task doesn't finish in time. The original task keeps running;WaitAsynconly stops waiting for it.new CancellationTokenSource(TimeSpan, TimeProvider)cancels its token after the delay.
With these, plus new PeriodicTimer(period, timeProvider) and timeProvider.CreateTimer, nothing in your code needs to touch the real clock directly.
A background service with PeriodicTimer
The typical production use is a hosted service that does periodic work. The TimeProvider is registered once in the container and injected (see Dependency injection with Microsoft.Extensions.DependencyInjection):
#:package Microsoft.Extensions.Hosting@10.0.13
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.ClearProviders().AddSimpleConsole(o => o.SingleLine = true)
.AddFilter("Microsoft.Hosting", LogLevel.Warning);
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddHostedService<HeartbeatService>();
using var host = builder.Build();
await host.StartAsync();
await Task.Delay(TimeSpan.FromSeconds(1.7));
await host.StopAsync();
class HeartbeatService(TimeProvider time, ILogger<HeartbeatService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(500), time);
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
logger.LogInformation("heartbeat at {Time:HH:mm:ss.f}", time.GetLocalNow());
}
}
catch (OperationCanceledException)
{
logger.LogInformation("heartbeat stopped");
}
}
}
info: HeartbeatService[0] heartbeat at 01:06:31.3
info: HeartbeatService[0] heartbeat at 01:06:31.8
info: HeartbeatService[0] heartbeat at 01:06:32.4
info: HeartbeatService[0] heartbeat stopped
stoppingToken is cancelled when the host shuts down, which ends the loop. In a real service, wrap the work inside the loop in its own try/catch: an unhandled exception in ExecuteAsync stops the service, and by default (since .NET 6) the whole host.
Periodic refresh is a common job for such a service, for example re-loading data into a cache before it goes stale. Caching itself is covered in the article "In-memory caching with IMemoryCache and HybridCache".
If you'd rather consume ticks with await foreach, a PeriodicTimer loop wraps naturally into an async iterator that yields each tick's time; see Async streams: IAsyncEnumerable and await foreach.
Testing with FakeTimeProvider
FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing is a TimeProvider whose clock only moves when you call Advance (or SetUtcNow). When the clock moves, it fires every timer that became due: PeriodicTimer ticks, ITimer callbacks, Task.Delay and WaitAsync timeouts created through the provider.
#:package Microsoft.Extensions.TimeProvider.Testing@10.11.0
using Microsoft.Extensions.Time.Testing;
var fake = new FakeTimeProvider();
Console.WriteLine($"start: {fake.GetUtcNow():yyyy-MM-dd HH:mm}");
Task delay = Task.Delay(TimeSpan.FromHours(1), fake);
fake.Advance(TimeSpan.FromMinutes(59));
Console.WriteLine($"after 59 min: delay completed = {delay.IsCompleted}");
fake.Advance(TimeSpan.FromMinutes(1));
Console.WriteLine($"after 60 min: delay completed = {delay.IsCompleted}");
var never = new TaskCompletionSource<int>();
Task<int> withTimeout = never.Task.WaitAsync(TimeSpan.FromSeconds(30), fake);
fake.Advance(TimeSpan.FromSeconds(30));
Console.WriteLine($"timeout: {withTimeout.Status}, {withTimeout.Exception?.InnerException?.GetType().Name}");
long ts = fake.GetTimestamp();
fake.Advance(TimeSpan.FromMilliseconds(1500));
Console.WriteLine($"elapsed: {fake.GetElapsedTime(ts)}");
start: 2000-01-01 00:00
after 59 min: delay completed = False
after 60 min: delay completed = True
timeout: Faulted, TimeoutException
elapsed: 00:00:01.5000000
An hour-long delay completes instantly, and exactly when expected. Without a start time, the fake clock begins at 2000-01-01 00:00 UTC.
Here is a polling loop that runs every 5 minutes, and a driver that simulates 17 minutes:
#:package Microsoft.Extensions.TimeProvider.Testing@10.11.0
using Microsoft.Extensions.Time.Testing;
var fake = new FakeTimeProvider(new DateTimeOffset(2026, 10, 18, 9, 0, 0, TimeSpan.Zero));
var poller = new Poller(fake, TimeSpan.FromMinutes(5));
using var cts = new CancellationTokenSource();
Task run = poller.RunAsync(cts.Token);
for (int i = 0; i < 3; i++)
{
fake.Advance(TimeSpan.FromMinutes(5));
await poller.Polled.WaitAsync(); // let the loop handle the tick
}
fake.Advance(TimeSpan.FromMinutes(2)); // less than a period: no poll
foreach (var t in poller.Polls)
Console.WriteLine($"polled at {t:HH:mm}");
Console.WriteLine($"now: {fake.GetUtcNow():HH:mm}, polls: {poller.Polls.Count}");
cts.Cancel();
await run;
Console.WriteLine("stopped");
class Poller(TimeProvider time, TimeSpan period)
{
public List<DateTimeOffset> Polls { get; } = [];
public SemaphoreSlim Polled { get; } = new(0);
public async Task RunAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(period, time);
try
{
while (await timer.WaitForNextTickAsync(ct))
{
Polls.Add(time.GetUtcNow());
Polled.Release();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
}
}
polled at 09:05
polled at 09:10
polled at 09:15
now: 09:17, polls: 3
stopped
The whole program runs in milliseconds and the result is the same every time.
Things to watch for:
- Create the timer before you advance.
RunAsyncruns synchronously up to its firstawait, so thePeriodicTimerexists by the timeAdvanceis called. If the loop starts on another thread (Task.Run, a hosted service), wait until it's ready, otherwise the firstAdvancehappens before the timer exists and fires nothing. - Advancing doesn't wait for your code.
Advancesignals the tick, but the loop body may still be running, or not yet started, when it returns. Since aPeriodicTimerremembers at most one tick, callingAdvancethree times in a row could produce a single poll. Give the code under test a way to signal that it handled a tick (the semaphore above), or advance one period at a time and wait for an observable effect. - Everything must go through the provider. A plain
Task.Delay(...),DateTime.UtcNowornew PeriodicTimer(period)without the provider reads the real clock, and the fake can't control it. AutoAdvanceAmountmakes everyGetUtcNow()call move the clock forward by a fixed step, which is useful for code that measures durations without timers.
How to use FakeTimeProvider inside xUnit tests, next to hand-written stubs and mocking libraries, is shown in Mocks and test doubles ("Built-in fakes for time and logging").
Summary
- For recurring async work, use
PeriodicTimerwith awhile (await timer.WaitForNextTickAsync(ct))loop. Ticks don't overlap and don't drift, and the loop ends on cancellation (exception) orDispose(false). - Use
System.Threading.Timer(orITimer) only when you really need a callback, and guard against overlapping callbacks. - Inject
TimeProviderinstead of readingDateTime.UtcNowand callingTask.Delaydirectly. RegisterTimeProvider.Systemin production. - Measure durations with
GetTimestamp()andGetElapsedTime(), orStopwatch.GetTimestamp()andStopwatch.GetElapsedTime()when no provider is involved. - Pass the provider to
PeriodicTimer,Task.Delay,WaitAsyncandCancellationTokenSource, and test withFakeTimeProvider.