.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

相关推荐
星星也在雾里4 小时前
PgBouncer 解决 PostgreSQL 连接数超限 + 可视化监控
数据库·postgresql
雨辰AI6 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
长城20246 小时前
关于MySql的ONLY_FULL_GROUP_BY问题
数据库·mysql·聚合列
常常有6 小时前
MySQL 底层执行原理:输入SQL语句到两阶段提交
数据库·sql·mysql
Mr. zhihao7 小时前
深入解析redis基本数据结构
数据结构·数据库·redis
m0_748839497 小时前
利用天正暖通CAD快速掌握风管数量统计的方法
数据库
随身数智备忘录7 小时前
什么是设备管理体系?设备管理体系包含哪些核心模块?
网络·数据库·人工智能
海市公约7 小时前
MySQL更新语句执行全流程:从Buffer Pool修改到二阶段提交
数据库·mysql·binlog·innodb·undo log·二阶段提交·update执行原理
颂love8 小时前
MySQL的执行流程
android·数据库·mysql
程序leo源8 小时前
Qt窗口详解
开发语言·数据库·c++·qt·青少年编程·c#