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

1、任务需求

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

2、代码实现

1)新建文件清理类

.NET Core 提供了BackgroundService的抽象类,在 ExecuteAsync 方法中执行特有的逻辑即可BackgroundService 类 -- 微软技术文档介绍https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=dotnet-plat-ext-6.0icon-default.png?t=LA92https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=dotnet-plat-ext-6.0

/// <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中注入文件清理服务

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

3、总结

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

学习链接地址

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

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

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

posted @ 2021-12-07 11:54  GoodTimeGGB  阅读(50)  评论(0编辑  收藏  举报