1 using Microsoft.Extensions.Configuration; 2 using Microsoft.Extensions.Hosting; 3 using Orleans; 4 using Star.Helpers; 5 using Star.IModuleServices. ...
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>();