.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

相关推荐
弈栈录3 小时前
MySQL 事务、索引与锁:后端开发必须掌握的数据库基础
数据库·后端
9624563 小时前
餐饮 SaaS 优惠券系统架构演进(三):优惠计算引擎——商品级计价、冲突策略与优惠分摊
java·数据库·spring boot
染指11103 小时前
135.Agent-多Agent框架-LangChain多智能体(SubAgents子代理)
数据库·人工智能·设计模式·langchain·agent·agents
Elastic 中国社区官方博客4 小时前
错误最多的服务运行正常:使用 ES|QL 从日志进行根因分析
大数据·运维·数据库·sql·elasticsearch·搜索引擎·全文检索
做运维的阿瑞4 小时前
mysql数据库视图笔记:创建、修改、删除与适用场景
数据库·笔记·mysql
Seraphina364 小时前
DVWA(SQL Injection-High,XSS Reflected-Medium,XSS Stored-Medium)
数据库·经验分享·sql·网络安全·xss
@Mike@4 小时前
12-数据库学习笔记(五种连接算法)
数据库·笔记·学习
Omics Pro5 小时前
之江实验室NAR|虚拟细胞3阶段训练范式
数据库·人工智能·算法·机器学习·自然语言处理
龙亘川5 小时前
探索智慧文化服务:建设初衷、整体架构、技术支撑、发展现状与实践影响
大数据·数据库·架构
风早爽太5 小时前
Python 学习笔记:数据库迁移工具 ‌Alembic
数据库·python·fastapi·alembic