netcore2.1 在后台运行一个任务
2024-09-04 14:30:43
在 ASP.NET Core 2.1中, 提供了一个名为BackgroundService的类,在 Microsoft.Extensions.Hosting命名空间中,其代码为
namespace Microsoft.Extensions.Hosting
{
//
// 摘要:
// Base class for implementing a long running Microsoft.Extensions.Hosting.IHostedService.
public abstract class BackgroundService : IHostedService, IDisposable
{
protected BackgroundService(); public virtual void Dispose();
//
// 摘要:
// Triggered when the application host is ready to start the service.
//
// 参数:
// cancellationToken:
// Indicates that the start process has been aborted.
public virtual Task StartAsync(CancellationToken cancellationToken);
//
// 摘要:
// Triggered when the application host is performing a graceful shutdown.
//
// 参数:
// cancellationToken:
// Indicates that the shutdown process should no longer be graceful.
[AsyncStateMachine(typeof(<StopAsync>d__4))]
public virtual Task StopAsync(CancellationToken cancellationToken);
//
// 摘要:
// This method is called when the Microsoft.Extensions.Hosting.IHostedService starts.
// The implementation should return a task that represents the lifetime of the long
// running operation(s) being performed.
//
// 参数:
// stoppingToken:
// Triggered when Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)
// is called.
//
// 返回结果:
// A System.Threading.Tasks.Task that represents the long running operations.
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
}
}
可以看出它是继承自 IHostedService, IDisposable , 而我们只需要继承并实现它的 ExecuteAsync 即可。
也就是说,我们只需在这个方法内写下这个服务需要做的事,
internal class TokenRefreshService : BackgroundService
{
private readonly ILogger _logger; public TokenRefreshService(ILogger<TokenRefresh2Service> logger)
{
_logger = logger;
} protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Service starting"); while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(DateTime.Now.ToLongTimeString() + ": Refresh Token!");//在此写需要执行的任务
await Task.Delay(, stoppingToken);
} _logger.LogInformation("Service stopping");
}
}
然后在Startup中注册服务。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TokenRefreshService>(); }
注意 注意 注意
1. 当IIS上部署的项目启动后,后台任务随之启动,任务执行相应的log正常输出。
2. 手动回收对应的应用程序池,任务执行相应的log输出停止。
3. 重新请求该网站,后台任务随之启动,任务执行相应的log重新开始输出。
所以不建议在这样的后台任务中做一些需要固定定时执行的业务处理类的操作,但对于缓存刷新类的操作还是可以的,因为当应用程序池回收后再次运行的时候,后台任务会随着启动。
最新文章
- hihoCoder#1135
- Map练习错误
- Android Studio新建一个HelloWorld 程序(App)
- C# 将文件转化成byte[]数组
- ajax载入数据是小细节
- hdu 1005 简单题
- WCF 下的windows服务的安装卸载
- ASP.NET (HttpModule,HttpHandler)
- 理解C++11正则表达式(2)
- (DT系列一)DTS结构及其编译方法
- //string scriptstrs = ";<;script>;alert(&#39;欢迎光临!&#39;);<;/script>;";;
- Oracle asm介绍和安装linux+oracle10g+asm过程
- IOC原理分析
- 分区数据库oracle自动分区
- 鸟哥Linux学习笔记04
- FusionCharts MSBar3D图
- xgb
- [Swift]LeetCode1013. 将数组分成和相等的三个部分 | Partition Array Into Three Parts With Equal Sum
- 怎么样启用红米手机5的ROOT权限
- 20165304学习基础和C语言基础调查
热门文章
- 【 React - 1/100 】React绑定事件this指向问题--改变state中的值
- win10文件夹共享
- JavaWeb中的文件上传和下载功能的实现
- java Thread源码分析
- 全文索引:部分词能查到,部分词查不到的bug
- CF1103D Codeforces Round #534 (Div. 1) Professional layer 状压 DP
- react 详细解析学习笔记
- ESP8266-12F
- 【leetcode】74. Search a 2D Matrix &; 240. Search a 2D Matrix II
- POST接口测试的请求方式