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 @ 2022-07-13 18:54  无心々菜  阅读(158)  评论(0编辑  收藏  举报