-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWorker.cs
40 lines (33 loc) · 1.21 KB
/
Worker.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
namespace WindowsService;
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private const string FolderToWatch = @"C:\WatchFolder";
private const int DelayInMilliseconds = 10000;
public Worker(ILogger<Worker> logger)
{
// we could (and should) inject configuration here
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// create FolderToWatch if it doesn't exist
if (!Directory.Exists(FolderToWatch)) Directory.CreateDirectory(FolderToWatch);
while (!stoppingToken.IsCancellationRequested)
{
// check FolderToWatch for files
var files = Directory.GetFiles(FolderToWatch);
// delete any file older than 1 minute
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
if (fileInfo.CreationTime < DateTime.Now.AddMinutes(-1))
{
_logger.LogInformation($"Deleting {fileInfo.Name}");
fileInfo.Delete();
}
}
await Task.Delay(DelayInMilliseconds, stoppingToken);
}
}
}