Skip to content

Instantly share code, notes, and snippets.

@skalahonza
Created September 30, 2021 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skalahonza/b17c6d42dfc03009b55a8158b4c368be to your computer and use it in GitHub Desktop.
Save skalahonza/b17c6d42dfc03009b55a8158b4c368be to your computer and use it in GitHub Desktop.
.NET SDK Background Service that can use CRON notation to run periodically.
public abstract class CrontabService : BackgroundService
{
private DateTime nextRun;
private readonly CrontabSchedule _schedule;
private readonly ILogger _logger;
public CrontabService(CrontabSchedule schedule, ILogger logger)
{
_schedule = schedule;
nextRun = _schedule.GetNextOccurrence(DateTime.Now);
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
do
{
var now = DateTime.Now;
_logger.LogInformation("Next run at: " + nextRun);
if (now > nextRun)
{
_logger.LogInformation("Running scheduled task.");
await Process(stoppingToken);
nextRun = _schedule.GetNextOccurrence(DateTime.Now);
}
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
}
while (!stoppingToken.IsCancellationRequested);
}
protected abstract Task Process(CancellationToken stoppingToken);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment