.net core background service

之前聊过如何在.net core 中添加后台服务,

当时使用的是BackgroundService的形式,这里使用IHostedService接口

csharp 复制代码
namespace oneModelMultiTable.BackgroundService
{
    public class EllisTest : IHostedService, IDisposable
    {
        private readonly ILogger<EllisTest> _logger;

        private Timer _timer;

        public EllisTest(ILogger<EllisTest> logger)
        {
            _logger = logger;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("start service");
            _timer = new Timer(Refresh, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("stop service");
            return Task.CompletedTask;
        }


        public void Refresh(object state)
        {
            _logger.LogInformation(DateTime.Now.ToString() + "测试定时任务");
        }
    }
}
csharp 复制代码
builder.Services.AddHostedService<EllisTest>();

StartAsync应该限于短时间运行的任务,因为托管服务是顺序运行的,并且在StartAsync运行完成之前不会启动其他服务。

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-7.0&tabs=visual-studio

相关推荐
AAA修煤气灶刘哥17 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud21 小时前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术1 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug1 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom1 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*1 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
Slaughter信仰1 天前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第十章知识点问答(10题)
java·jvm·数据库
麦兜*1 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
-Xie-1 天前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存