-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScheduledBackgroundService.cs
More file actions
42 lines (35 loc) · 1.63 KB
/
ScheduledBackgroundService.cs
File metadata and controls
42 lines (35 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NCrontab;
namespace ScheduledBackgroundService
{
public abstract class ScheduledBackgroundService : BackgroundService
{
private readonly ILogger _logger;
private CrontabSchedule _crontabSchedule;
public ScheduledBackgroundService(ILogger logger, string cronExpression)
{
_logger = logger;
var includingSeconds = new CrontabSchedule.ParseOptions { IncludingSeconds = true };
_crontabSchedule = CrontabSchedule.Parse(cronExpression, includingSeconds);
_logger.LogDebug($"cronExpression: [{cronExpression}]");
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var utcNow = DateTime.UtcNow;
var nextOccurrenceDateTime = _crontabSchedule.GetNextOccurrence(utcNow);
var durationToNextOccurrence = (nextOccurrenceDateTime - utcNow);
_logger.LogDebug($"Scheduled execution for, {nextOccurrenceDateTime.ToString("o")}");
await Task.Delay(durationToNextOccurrence, stoppingToken);
_logger.LogDebug($"Started execution at [{DateTime.UtcNow.ToString("o")}]");
await ExecuteAtScheduledTimeAsync(stoppingToken);
}
}
protected abstract Task ExecuteAtScheduledTimeAsync(CancellationToken stoppingToken);
}
}