ASP.NET Core 2.1 : 十一. 如何在后台运行一个任务

在大部分程序中一般都会需要用到后台任务, 比如定时更新缓存或更新某些状态。(asp.net core 系列目录

一、应用场景

以调用微信公众号的api为例, 经常会用到access_token,官方文档这样描述:“是公众号的全局唯一接口调用凭据,有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效,建议公众号开发者使用中控服务器统一获取和刷新access_token,其他业务逻辑服务器所使用的access_token均来自于该中控服务器,不应该各自去刷新,否则容易造成冲突,导致access_token覆盖而影响业务。”

在这个场景中我们可以创建一个后台运行的服务,按照access_token的有效期定时执行去请求获取新的access_token并存储,其他所有需要用到这个access_token的都到这个共有的access_token。

二、实现方式(一)

asp.net core 在2.0的时候就提供了一个名为ihostedservice的接口,我们要做的只有两件事:

1. 实现它。

2. 将这个接口实现注册到依赖注入服务中。

a. 实现ihostedservice的接口

首先看一下这个ihostedservice:

    public interface ihostedservice
    {
        task startasync(cancellationtoken cancellationtoken);
        task stopasync(cancellationtoken cancellationtoken);
    }

通过名字就可以看出来,一个是这个服务启动的时候做的操作,另一个则是停止的时候。

新建一个类 tokenrefreshservice  实现 ihostedservice ,如下面代码所示:

 1     internal class tokenrefreshservice : ihostedservice, idisposable
 2     {
 3         private readonly ilogger _logger;
 4         private timer _timer;
 5 
 6         public tokenrefreshservice(ilogger<tokenrefreshservice> logger)
 7         {
 8             _logger = logger;
 9         }
10 
11         public task startasync(cancellationtoken cancellationtoken)
12         {
13             _logger.loginformation("service starting");
14             _timer = new timer(refresh, null, timespan.zero,timespan.fromseconds(5));
15             return task.completedtask;
16         }
17 
18         private void refresh(object state)
19         {
20             _logger.loginformation(datetime.now.tolongtimestring() + ": refresh token!"); //在此写需要执行的任务
21             
22         }
23 
24         public task stopasync(cancellationtoken cancellationtoken)
25         {
26             _logger.loginformation("service stopping");
27             _timer?.change(timeout.infinite, 0);
28             return task.completedtask;
29         }
30 
31         public void dispose()
32         {
33             _timer?.dispose();
34         }
35     }

既然是定时刷新任务,那么就用了一个timer, 当服务启动的时候启动它,由它定时执行refresh方法来获取新的token。

这里为了方便测试写了5秒执行一次, 实际应用还是读取配置文件比较好, 结果如下:

backservice.tokenrefreshservice:information: 17:23:30: refresh token!
backservice.tokenrefreshservice:information: 17:23:35: refresh token!
backservice.tokenrefreshservice:information: 17:23:40: refresh token!
backservice.tokenrefreshservice:information: 17:23:45: refresh token!
backservice.tokenrefreshservice:information: 17:23:50: refresh token!

b. 在依赖注入中注册这个服务。

在startup的configureservices中注册这个服务,如下代码所示:

services.addsingleton<ihostedservice, tokenrefreshservice>();

三、实现方式(二)

在 asp.net core 2.1中, 提供了一个名为 backgroundservice  的类,它在 microsoft.extensions.hosting 命名空间中,查看一下它的源码:

 1 using system;
 2 using system.threading;
 3 using system.threading.tasks;
 4 
 5 namespace microsoft.extensions.hosting
 6 {
 7     /// <summary>
 8     /// base class for implementing a long running <see cref="ihostedservice"/>.
 9     /// </summary>
10     public abstract class backgroundservice : ihostedservice, idisposable
11     {
12         private task _executingtask;
13         private readonly cancellationtokensource _stoppingcts = new cancellationtokensource();
14 
15         /// <summary>
16         /// this method is called when the <see cref="ihostedservice"/> starts. the implementation should return a task that represents
17         /// the lifetime of the long running operation(s) being performed.
18         /// </summary>
19         /// <param name="stoppingtoken">triggered when <see cref="ihostedservice.stopasync(cancellationtoken)"/> is called.</param>
20         /// <returns>a <see cref="task"/> that represents the long running operations.</returns>
21         protected abstract task executeasync(cancellationtoken stoppingtoken);
22 
23         /// <summary>
24         /// triggered when the application host is ready to start the service.
25         /// </summary>
26         /// <param name="cancellationtoken">indicates that the start process has been aborted.</param>
27         public virtual task startasync(cancellationtoken cancellationtoken)
28         {
29             // store the task we're executing
30             _executingtask = executeasync(_stoppingcts.token);
31 
32             // if the task is completed then return it, this will bubble cancellation and failure to the caller
33             if (_executingtask.iscompleted)
34             {
35                 return _executingtask;
36             }
37 
38             // otherwise it's running
39             return task.completedtask;
40         }
41 
42         /// <summary>
43         /// triggered when the application host is performing a graceful shutdown.
44         /// </summary>
45         /// <param name="cancellationtoken">indicates that the shutdown process should no longer be graceful.</param>
46         public virtual async task stopasync(cancellationtoken cancellationtoken)
47         {
48             // stop called without start
49             if (_executingtask == null)
50             {
51                 return;
52             }
53 
54             try
55             {
56                 // signal cancellation to the executing method
57                 _stoppingcts.cancel();
58             }
59             finally
60             {
61                 // wait until the task completes or the stop token triggers
62                 await task.whenany(_executingtask, task.delay(timeout.infinite, cancellationtoken));
63             }
64         }
65 
66         public virtual void dispose()
67         {
68             _stoppingcts.cancel();
69         }
70     }
71 }

可以看出它一样是继承自 ihostedservice, idisposable , 它相当于是帮我们写好了一些“通用”的逻辑, 而我们只需要继承并实现它的 executeasync 即可。

也就是说,我们只需在这个方法内写下这个服务需要做的事,这样上面的刷新token的service就可以改写成这样:

 1     internal class tokenrefreshservice : backgroundservice
 2     {
 3         private readonly ilogger _logger;
 4 
 5         public tokenrefreshservice(ilogger<tokenrefresh2service> logger)
 6         {
 7             _logger = logger;
 8         }
 9 
10         protected override async task executeasync(cancellationtoken stoppingtoken)
11         {
12             _logger.loginformation("service starting");
13 
14             while (!stoppingtoken.iscancellationrequested)
15             {
16                 _logger.loginformation(datetime.now.tolongtimestring() + ": refresh token!");//在此写需要执行的任务
17                 await task.delay(5000, stoppingtoken);
18             }
19 
20             _logger.loginformation("service stopping");
21         }
22     }

是不是简单了不少。(同样这里为了方便测试写了5秒执行一次)

四. 注意事项

感谢@ 咿呀咿呀哟在评论中的提醒,当项目部署在iis上的时候, 当应用程序池回收的时候,这样的后台任务也会停止执行。

经测试:

1. 当iis上部署的项目启动后,后台任务随之启动,任务执行相应的log正常输出。

2. 手动回收对应的应用程序池,任务执行相应的log输出停止。

3. 重新请求该网站,后台任务随之启动,任务执行相应的log重新开始输出。

所以不建议在这样的后台任务中做一些需要固定定时执行的业务处理类的操作,但对于缓存刷新类的操作还是可以的,因为当应用程序池回收后再次运行的时候,后台任务会随着启动。

github地址

本文链接:https://2i3i.com/aspnetcore2_11.html ,转载请注明来源地址。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇