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>();