Created
September 30, 2021 06:59
-
-
Save skalahonza/b17c6d42dfc03009b55a8158b4c368be to your computer and use it in GitHub Desktop.
.NET SDK Background Service that can use CRON notation to run periodically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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