前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.NET Core 项目启动时运行定时任务

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

原创
作者头像
GoodTime
发布2023-10-31 11:17:52
4150
发布2023-10-31 11:17:52
举报
文章被收录于专栏:GoodTime的全栈开发

1、任务需求

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

2、代码实现

1)新建文件清理类

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

BackgroundService 类 -- 微软技术文档介绍

代码语言:c#
复制
/// <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中注入文件清理服务

代码语言:c#
复制
public void ConfigureServices(IServiceCollection services)
{
    // 注入定时清理文件服务
    services.AddSingleton<IHostedService, ScheduledCleanUpFileService>();
}

3、总结

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

学习链接地址

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

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

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

以上就是.NET Core 项目启动时运行定时任务的介绍,做此记录,如有帮助,欢迎点赞关注收藏!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、任务需求
  • 2、代码实现
    • 1)新建文件清理类
      • 2)在StartUp.cs中注入文件清理服务
        • 以上就是.NET Core 项目启动时运行定时任务的介绍,做此记录,如有帮助,欢迎点赞关注收藏!
    • 3、总结
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档