-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteOldFiles.cs
More file actions
74 lines (59 loc) · 2.21 KB
/
Copy pathDeleteOldFiles.cs
File metadata and controls
74 lines (59 loc) · 2.21 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class DeleteOldFiles : IHostedLifecycleService
{
private Task? executingTask;
private CancellationTokenSource stoppingCts = new CancellationTokenSource();
private readonly Settings settings;
public DeleteOldFiles(Settings settings)
{
this.settings = settings;
}
public Task StartingAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Starting Service");
return Task.CompletedTask;
}
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Start Service");
return Task.CompletedTask;
}
public async Task StartedAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Started Service");
executingTask = ExecuteAsync(stoppingCts.Token);
// If the task is completed, return it, otherwise it's still running
await (executingTask.IsCompleted ? executingTask : Task.CompletedTask);
}
protected async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine($"Delete file {DateTime.Now:HH:mm:ss}");
foreach (string file in Directory.GetFiles(settings.GetUserTempPath()))
{
var fi = new FileInfo(file);
if (fi.CreationTimeUtc < DateTime.UtcNow.AddMinutes(-settings.DeleteFilesOlderThanMinutes))
fi.Delete();
}
await Task.Delay(settings.DeleteFilesOlderThanMinutes * 60 * 1000, stoppingToken);
}
Console.WriteLine("Execution stopped");
}
public Task StoppingAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Stopping Service");
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Stop Service");
stoppingCts.Cancel();
if (executingTask is not null)
await Task.WhenAny(executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
}
public Task StoppedAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Stopped Service");
return Task.CompletedTask;
}
}