zoukankan      html  css  js  c++  java
  • 如何在ASP.NET Core项目启动时执行异步定时任务

    背景介绍

      项目环境为ASP.NET Core 2.1.2。

      需要在项目启动时运行一个定时任务,在后台每隔一定时间执行任务。

    实现方法

      1、写一个任务服务类继承BackgroundService

    public class APIDataService : BackgroundService
        {
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        //需要执行的任务
    
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex.Message);
                    }
                    await Task.Delay(1000, stoppingToken);//等待1秒
                }
            }
        }
    

     2、在Startup.cs中注入

    public void ConfigureServices(IServiceCollection services)
    {
           ......
      services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, APIDataService>();
    }
    
    锲而舍之,朽木不折;锲而不舍,金石可镂。
  • 相关阅读:
    epoll oneshot
    回望五月
    都知道的copy_from_user
    ixgbe 驱动 为xxx驱动做准备1
    面试问题集锦
    数据治理
    阅读
    hive 数据仓库面试题目集锦
    面试小问题集锦
    Scala学习笔记~尚硅谷学习视频
  • 原文地址:https://www.cnblogs.com/zhengyb/p/14298300.html
Copyright © 2011-2022 走看看