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
|
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) { 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启动时运行异步任务(二)