.net core 简单定时程序

1 using Microsoft.Extensions.Configuration;
 2 using Microsoft.Extensions.Hosting;
 3 using Orleans;
 4 using Star.Helpers;
 5 using Star.IModuleServices.Common.Interfaces.System;
 6 using Star.IModuleServices.Common.Models.System.SettingHotUpdate.Responses;
 7 using System;
 8 using System.Collections.Concurrent;
 9 using System.Collections.Generic;
10 using System.Threading;
11 using System.Threading.Tasks;
12 using Star.Service.Project.Admin.Tool.ConfigTime;
13 namespace Star.Service.Project.Admin.Tool.ConfigTime
14 {
15     /// <summary>
16     /// 简单的定时任务执行
17     /// </summary>
18     public class TimedExecutService : BackgroundService
19     {
20         protected override async Task ExecuteAsync(CancellationToken stoppingToken)
21         {
22             try
23             {
24                 Console.WriteLine(DateTime.Now.ToString() + "BackgroundService:启动");
25
26                 while (!stoppingToken.IsCancellationRequested)
27                 {
28                     await Task.Delay(5000, stoppingToken); //启动后5秒执行一次 (用于测试)
29                     //数据源
30                     ApiResult<List<SysSettingHotUpdateResponseDto>> list = new ApiResult<List<SysSettingHotUpdateResponseDto>>();
31                     try
32                     {
33                         var cluster = Ioc.GetService<IClusterClient>();
34                         list = await cluster.GetGrain<ISysSettingHotUpdate>(0).GetList("Star.Service.Project.Admin");
35                     }
36                     catch (Exception ex)
37                     {
38                         throw new Exception("未获取到相关配置:" + ex.Message);
39                     }
40
41                     if (list.Data.Count <= 0)
42                     {
43                         throw new Exception("未获取到相关配置");
44                     }
45                     //自定义数据处理
46                     ConfigData.Data = new ConcurrentDictionary<string, string>();
47                     list.Data.ForEach(c =>
48                     {
49                         ConfigData.Data[c.K] = c.V;
50                     });
51                     Console.WriteLine(DateTime.Now.ToString() + " 执行逻辑");
52                 }
53                 Console.WriteLine(DateTime.Now.ToString() + "BackgroundService:停止");
54             }
55             catch (Exception ex)
56             {
57                 if (!stoppingToken.IsCancellationRequested)
58                 {
59                     Console.WriteLine(DateTime.Now.ToString() + "BackgroundService:异常" + ex.Message + ex.StackTrace);
60                 }
61                 else
62                 {
63                     Console.WriteLine(DateTime.Now.ToString() + "BackgroundService:停止");
64                 }
65             }
66         }
67
68     }
69 }

注入定时任务:
services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TimedExecutService>();

(0)

相关推荐