-
Notifications
You must be signed in to change notification settings - Fork 149
/
MessagePersistenceBackgroundService.cs
66 lines (56 loc) · 2.27 KB
/
MessagePersistenceBackgroundService.cs
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using BuildingBlocks.Abstractions.Messaging.PersistMessage;
using BuildingBlocks.Abstractions.Types;
using BuildingBlocks.Core.Messaging.MessagePersistence;
using BuildingBlocks.Core.Web.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace BuildingBlocks.Core.Messaging.BackgroundServices;
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services
public class MessagePersistenceBackgroundService(
ILogger<MessagePersistenceBackgroundService> logger,
IOptions<MessagePersistenceOptions> options,
IServiceProvider serviceProvider,
IHostApplicationLifetime lifetime,
IMachineInstanceInfo machineInstanceInfo
) : BackgroundService
{
private readonly MessagePersistenceOptions _options = options.Value;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!await lifetime.WaitForAppStartup(stoppingToken))
{
return;
}
logger.LogInformation(
"MessagePersistence Background Service is starting on client '{@ClientId}' and group '{@ClientGroup}'",
machineInstanceInfo.ClientId,
machineInstanceInfo.ClientGroup
);
await ProcessAsync(stoppingToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation(
"MessagePersistence Background Service is stopping on client '{@ClientId}' and group '{@ClientGroup}'",
machineInstanceInfo.ClientId,
machineInstanceInfo.ClientGroup
);
return base.StopAsync(cancellationToken);
}
private async Task ProcessAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await using (var scope = serviceProvider.CreateAsyncScope())
{
var service = scope.ServiceProvider.GetRequiredService<IMessagePersistenceService>();
await service.ProcessAllAsync(stoppingToken);
}
var delay = _options.Interval is { }
? TimeSpan.FromSeconds((int)_options.Interval)
: TimeSpan.FromSeconds(30);
await Task.Delay(delay, stoppingToken);
}
}
}