-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
58 lines (52 loc) · 2.88 KB
/
Program.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
using Polly.Retry;
using Polly;
using Tingle.PeriodicTasks;
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var environment = context.HostingEnvironment;
var configuration = context.Configuration;
// register IDistributedLockProvider
var path = configuration.GetValue<string?>("DistributedLocking:FilePath")
?? Path.Combine(environment.ContentRootPath, "distributed-locks");
services.AddSingleton<Medallion.Threading.IDistributedLockProvider>(provider =>
{
return new Medallion.Threading.FileSystem.FileDistributedSynchronizationProvider(Directory.CreateDirectory(path));
});
// register periodic tasks
services.AddPeriodicTasks(builder =>
{
builder.AddTask<DatabaseCleanerTask>(o =>
{
o.Schedule = "*/1 * * * *";
o.ResiliencePipeline = new ResiliencePipelineBuilder()
.AddRetry(new RetryStrategyOptions
{
ShouldHandle = new PredicateBuilder().Handle<Exception>(),
Delay = TimeSpan.FromSeconds(1),
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Constant,
OnRetry = args =>
{
Console.WriteLine($"Attempt {args.AttemptNumber} failed; retrying in {args.RetryDelay}");
return ValueTask.CompletedTask;
},
})
.Build();
});
});
})
.Build();
await host.RunAsync();
class DatabaseCleanerTask(ILogger<DatabaseCleanerTask> logger) : IPeriodicTask
{
public async Task ExecuteAsync(PeriodicTaskExecutionContext context, CancellationToken cancellationToken = default)
{
if (Random.Shared.Next(1, 5) > 2) // 60% of the time
{
throw new Exception("Failed to clean up old records from the database");
}
logger.LogInformation("Cleaned up old records from the database");
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
}