blob: 48cdf2f6a530d7e3c0ed1ea361b49c42402276c7 (
plain)
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
|
namespace Elements.Backend.Services;
class PeriodicService : BackgroundService
{
private readonly TimeSpan _period = TimeSpan.FromMinutes(1);
private readonly ILogger<PeriodicService> _logger;
private readonly IServiceScopeFactory _factory;
public bool IsEnabled { get; set; } = true;
public PeriodicService(
ILogger<PeriodicService> logger,
IServiceScopeFactory factory)
{
_logger = logger;
_factory = factory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using PeriodicTimer timer = new PeriodicTimer(_period);
while (
!stoppingToken.IsCancellationRequested &&
await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
if (!IsEnabled) continue;
await using AsyncServiceScope asyncScope = _factory.CreateAsyncScope();
FinishVoteService finishVoteService = asyncScope.ServiceProvider.GetRequiredService<FinishVoteService>();
await finishVoteService.DoSomethingAsync();
}
catch (Exception ex)
{
_logger.LogInformation($"Failed to execute periodic service, Error: {ex.Message}.");
}
}
}
}
|