如何在ASP.NET Core项目启动时执行异步定时任务

背景介绍

  项目环境为ASP.NET Core 2.1.2。

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

实现方法

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

 1     public class APIDataService : BackgroundService
 2     {
 3         protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 4         {
 5             while (!stoppingToken.IsCancellationRequested)
 6             {
 7                 try
 8                 {
 9                     //需要执行的任务
10 
11                 }
12                 catch (Exception ex)
13                 {
14                     LogHelper.Error(ex.Message);
15                 }
16                 await Task.Delay(1000, stoppingToken);//等待1秒
17             }
18         }
19     }

  2、在Startup.cs中注入

1 public void ConfigureServices(IServiceCollection services)
2 {
3   ...
4   services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, APIDataService>();
5 }

  3、运行代码,进行测试

posted @ 2020-03-27 08:57  薄心之心  阅读(2929)  评论(0编辑  收藏  举报