.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

相关推荐
SelectDB18 小时前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶19 小时前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵1 天前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
Nturmoils1 天前
WHERE 条件别凭习惯写,常用查询先跑一遍
数据库
Databend2 天前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
ClouGence3 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
飞将3 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils4 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波4 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_5 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库