Advertisement
Intermediate .NET, Background Services

How would you implement a scheduled (cron-like) background job in .NET without a third-party library?

Short answer

You can implement basic scheduling by calculating the delay until the next desired execution time inside your ExecuteAsync loop (e.g., using a library like Cronos to parse cron expressions and compute next occurrence, or simple DateTime math for fixed schedules), then…

Save .NET mock interview
Advertisement
AModel answer
You can implement basic scheduling by calculating the delay until the next desired execution time inside your ExecuteAsync loop (e.g., using a library like Cronos to parse cron expressions and compute next occurrence, or simple DateTime math for fixed schedules), then Task.Delay-ing until that time before running the job and recalculating the next occurrence -- for more complex scheduling needs, dedicated libraries like Hangfire or Quartz.NET are usually preferred.
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    var schedule = CronExpression.Parse("0 2 * * *");  // 2 AM daily, via Cronos
    while (!stoppingToken.IsCancellationRequested) {
        var next = schedule.GetNextOccurrence(DateTimeOffset.UtcNow);
        var delay = next.Value - DateTimeOffset.UtcNow;
        await Task.Delay(delay, stoppingToken);
        await RunNightlyReportAsync();
    }
}
Real-world example
A reporting background service runs a nightly summary job at exactly 2 AM using a cron expression parsed with Cronos, rather than hardcoding a fixed Task.Delay that would drift relative to wall-clock time over daylight saving transitions.
Likely follow-ups
  • When should you reach for Quartz.NET or Hangfire instead of hand-rolling scheduling?
  • How do you handle a missed scheduled run if the app was down at the scheduled time?
Related topics