Recipe 14.2 · C#
Running at a Time of Day
Problem
The billing job must run at 2:00 a.m. Eastern time every day. Not every 24 hours from whenever the service was last restarted, and not twice on the night the clocks go back.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: misses runs, double-runs, server-local time
while (true)
{
if (DateTime.Now.Hour == 2 && DateTime.Now.Minute == 0)
{
RunBilling();
}
Thread.Sleep(60000);
}
If RunBilling takes less than a minute, it runs twice within the 2:00 minute. If the check
happens at 1:59:59.9 and then again at 2:01:00.1, it doesn't run at all. DateTime.Now is the
server's local time, which on a cloud VM is usually UTC. And on the night the clocks change, 2:00
a.m. happens twice in the autumn and not at all in the spring. DateTime.Now appears in about
19,999 hand-written C# files in the archive, across 33 engagements, and code like this is one of
the reasons it matters.
The improved recipe
Compute the next run time as an instant, wait until then, run, and repeat. Keep the calculation in its own class so the daylight-saving rules can be tested without waiting for March.
using System;
namespace ImproveCode.Jobs;
public sealed class DailySchedule(TimeOnly runAt, TimeZoneInfo zone)
{
public TimeOnly RunAt { get; } = runAt;
public TimeZoneInfo Zone { get; } = zone;
public DateTimeOffset GetNextOccurrence(DateTimeOffset after)
{
DateTime localNow = TimeZoneInfo.ConvertTime(after, Zone).DateTime;
DateTime candidate = localNow.Date + RunAt.ToTimeSpan();
if (candidate <= localNow)
{
candidate = candidate.AddDays(1);
}
// During the repeated autumn hour, today's first 1:30 may
// already be in the past. Never return an earlier instant.
DateTimeOffset next = ToInstant(candidate);
return next > after ? next : ToInstant(candidate.AddDays(1));
}
private DateTimeOffset ToInstant(DateTime local)
{
// Spring forward: 2:30 does not exist, run at the first
// valid minute after it.
while (Zone.IsInvalidTime(local))
{
local = local.AddMinutes(1);
}
// Fall back: 1:30 happens twice, run at the first one.
TimeSpan offset = Zone.IsAmbiguousTime(local)
? Max(Zone.GetAmbiguousTimeOffsets(local))
: Zone.GetUtcOffset(local);
return new DateTimeOffset(local, offset);
}
private static TimeSpan Max(TimeSpan[] offsets)
{
TimeSpan max = offsets[0];
foreach (TimeSpan offset in offsets)
{
if (offset > max)
{
max = offset;
}
}
return max;
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Jobs;
public sealed class DailyJobService<TJob>(
DailySchedule schedule,
IServiceScopeFactory scopes,
TimeProvider time,
ILogger<DailyJobService<TJob>> logger) : BackgroundService
where TJob : class, IScheduledJob
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
DateTimeOffset now = time.GetUtcNow();
DateTimeOffset next = schedule.GetNextOccurrence(now);
logger.LogInformation("{Job} next run at {Next:u}",
typeof(TJob).Name, next);
await Task.Delay(next - now, time, stoppingToken);
try
{
await using AsyncServiceScope scope =
scopes.CreateAsyncScope();
await scope.ServiceProvider
.GetRequiredService<TJob>()
.RunAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "{Job} failed", typeof(TJob).Name);
}
}
}
}
Registration, with the time zone given by its IANA name:
var zone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<NightlyBillingRun>();
builder.Services.AddHostedService(sp =>
new DailyJobService<NightlyBillingRun>(
new DailySchedule(new TimeOnly(2, 0), zone),
sp.GetRequiredService<IServiceScopeFactory>(),
sp.GetRequiredService<TimeProvider>(),
sp.GetRequiredService<
ILogger<DailyJobService<NightlyBillingRun>>>()));
How it works
GetNextOccurrence converts "now" into the business time zone, builds today's run time on the
wall clock, and moves to tomorrow if that time has passed. Only then does it convert back to an
instant. Working on the wall clock is what keeps the job at 2:00 local time across the change from
standard time to daylight time, when the UTC time of the run shifts by an hour.
ToInstant handles the two awkward nights. In spring, local times between 2:00 and 3:00 don't
exist, and IsInvalidTime returns true. The loop moves forward to the first valid minute, so a
2:30 job runs at 3:00 that night instead of being skipped. In autumn, 1:00 to 2:00 happens twice,
and GetAmbiguousTimeOffsets returns both offsets. The larger offset is the earlier instant, the
first time the clock shows 1:30, so the job runs once. A service restarted during the repeated
hour would otherwise compute an instant that has already passed, so the method moves to the next
day whenever the result is not later than after.
I tested these cases for America/New_York around the 2026 changes: a 2:30 run on 8 March came
out at 3:00 local (07:00 UTC), and a 1:30 run on 1 November came out at 05:30 UTC, the first
occurrence, exactly once.
Task.Delay(TimeSpan, TimeProvider, CancellationToken) waits on the injected clock. In production
that is TimeProvider.System. In tests, FakeTimeProvider from the
Microsoft.Extensions.TimeProvider.Testing package lets you advance time by a day in a
microsecond and assert that the job ran.
Variations and pitfalls
- Store the time zone, not an offset.
-05:00is right for half the year. An IANA name such asAmerica/New_York(supported on Windows since .NET 6) or a Windows ID such asEastern Standard Timecarries the rules. - Missed runs. If the server is down at 2:00, this service does not catch up when it returns. If a missed run must happen, record the last successful run date in the database and run at start-up when it is older than today.
- Several times a day or business days only. Generalize
DailyScheduleto anIScheduleinterface withGetNextOccurrence. For anything that reads like a cron expression, use the scheduler in Recipe 14.6 rather than writing a cron parser. Chapter 15 covers business-day calculations.