.NET Core 项目启动时运行定时任务


1、任务需求

在每次服务启动时定时(如24小时)清理一次缓存文件

2、代码实现

1)新建文件清理类

.NET Core 提供了BackgroundService的抽象类,在 ExecuteAsync 方法中执行特有的逻辑即可

BackgroundService 类 – 微软技术文档介绍

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
/// <summary>
/// 定时清理文件
/// </summary>
public class ScheduledCleanUpFileService: BackgroundService
{
private readonly ILogger _logger;
private CancellationTokenSource tokenSource;
public ScheduledCleanUpFileService(ILogger<ScheduledCleanUpFileService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if(!stoppingToken.IsCancellationRequested)
{
// 24小时清理一次文件
await Task.Delay(86400000, stoppingToken).ContinueWith(x =>
{
// 需要执行的任务
try
{
var filePath = AppDomain.CurrentDomain.BaseDirectory + "AppFileUploads/";
DirectoryInfo info = new DirectoryInfo(filePath);
// 去除文件夹的只读属性
info.Attributes = FileAttributes.Normal & FileAttributes.Directory;
// 去除文件的只读属性
File.SetAttributes(filePath, FileAttributes.Normal);
// 判断文件夹是否存在
if(Directory.Exists(filePath))
{
foreach(var file in Directory.GetFileSystemEntries(filePath))
{
if(File.Exists(file))
{
// 如果有子文件则删除子文件的所有文件
File.Delete(file);
}
}
}
}
catch(Exception ex)
{
_logger.LogError(ex, ex.Message);
}
});
}
else
{
await StopAsync(stoppingToken);
}
}
public override Task StartAsync(CancellationToken cancellationToken)
{
tokenSource = new CancellationTokenSource();
_logger.LogInformation("开始定时清理文件任务");
return base.StartAsync(tokenSource.Token);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
tokenSource.Cancel();
_logger.LogInformation("定时清理文件任务结束");
return base.StopAsync(tokenSource.Token);
}
}

2)在StartUp.cs中注入文件清理服务

1
2
3
4
5
public void ConfigureServices(IServiceCollection services)
{
// 注入定时清理文件服务
services.AddSingleton<IHostedService, ScheduledCleanUpFileService>();
}

3、总结

由此实现服务启动时每隔24小时执行一次文件清理服务

学习链接地址

【5min+】后台任务的积木。.NetCore中的IHostedService

ASP.NET Core 3.x启动时运行异步任务(一)

ASP.NET Core 3.x启动时运行异步任务(二)


文章作者: GoodTimeGGB
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 GoodTimeGGB !
评论
  目录