.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

相关推荐
AOwhisky7 小时前
MySQL 学习笔记(第四期):SQL 语言之多表查询
linux·运维·网络·数据库·笔记·学习·mysql
小红卒8 小时前
mysql之udf提权
数据库·mysql·网络安全
Trouvaille ~8 小时前
【Redis篇】Redis 哨兵(Sentinel):高可用自动故障转移
数据库·redis·缓存·中间件·sentinel·高可用·哨兵
qfljg8 小时前
oracle 迁移到postgres
数据库·oracle
giaz14n9X9 小时前
Redis 分布式锁进阶第五十七篇
数据库·redis·分布式
剑神一笑9 小时前
Linux ls 命令深度解析:从目录遍历到颜色输出的实现原理
linux·服务器·数据库
Maynor9969 小时前
Codex API 网关迁移与流量优化实战
数据库·oracle
WyCAGy8ij10 小时前
Redis 分布式锁进阶第二篇讲解
数据库·redis·分布式
南极企鹅10 小时前
MySQL的两大支柱:undo Log&redo log
数据库·mysql·oracle
智航GIS10 小时前
ArcGIS大师之路500技---078文件数据库的加密与解密
数据库·arcgis