NETCORE - IHostedService定时任务的使用

NETCORE - IHostedService定时任务的使用

 

项目环境,net core 3.1 + webapi 

 

安装依赖:

Microsoft.Extensions.Hosting.Abstractions

 

 

 

1. 在startup.cs中注册 

// .Net 6
builder.Services.AddHostedService<TestHostedService>();

// .Net  5 及以下
services.AddHostedService<TestHostedService>();

 

 2. 新增 TestHostedService 定时任务类

复制代码
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace NETCORE.IHostedServiceJob
{
    public class TestHostedService : IHostedService, IDisposable
    {
        private Timer? _timer;

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

            return Task.CompletedTask;
        }

        private void DoWork(object? state)
        {
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("StopAsync");

            return Task.CompletedTask;
        }


        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}
复制代码

 

 

 运行

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

引用:https://www.cnblogs.com/ysmc/p/16456787.html

 

posted @   无心々菜  阅读(163)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示