Last active
February 19, 2021 19:18
-
-
Save ankitvijay/9e0d35e00cbeda3833614737ac64b9bf to your computer and use it in GitHub Desktop.
Schedule Job every one min
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
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Cronos; | |
using Microsoft.Extensions.Hosting; | |
using Microsoft.Extensions.Logging; | |
namespace SchedulerJobSample.Worker | |
{ | |
public class SchedulerService : BackgroundService | |
{ | |
private readonly ILogger<SchedulerService> _logger; | |
public SchedulerService(ILogger<SchedulerService> logger) | |
{ | |
_logger = logger; | |
} | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
while (!stoppingToken.IsCancellationRequested) | |
{ | |
// Schedule the job every minute. | |
await WaitForNextSchedule("* * * * *"); | |
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); | |
} | |
} | |
private async Task WaitForNextSchedule(string cronExpression) | |
{ | |
var parsedExp = CronExpression.Parse(cronExpression); | |
var currentUtcTime = DateTimeOffset.UtcNow.UtcDateTime; | |
var occurenceTime = parsedExp.GetNextOccurrence(currentUtcTime); | |
var delay = occurenceTime.GetValueOrDefault() - currentUtcTime; | |
_logger.LogInformation("The run is delayed for {delay}. Current time: {time}", delay, DateTimeOffset.Now); | |
await Task.Delay(delay); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment