原文链接:https://blog.csdn.net/x1234w4321/article/details/140797306
namespace XCGWebApp.TimerService
{
    /// <summary>
    /// 后台定时任务
    /// </summary>
    public class TimerBackgroundService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                // 这里是你的定时任务逻辑  
                Console.WriteLine($"任务执行于: {DateTime.Now}");
                // 等待一段时间 10秒 再执行下一次  
                await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
            }
        }
    }
}

注入服务 builder.Services.AddHostedService<TimerBackgroundService>();
也可以使用AutoFac注入服务:https://blog.csdn.net/qq_41942413/article/details/134321023

posted on 2024-08-22 11:29  邢帅杰  阅读(20)  评论(0编辑  收藏  举报