aspnet core运行后台服务任务
之前在公司的一个项目中需要用到定时程序,当时使用的是aspnet core提供的IHostedService接口来实现后台定时程序,具体的示例可去官网查看。现在的dotnet core中默认封装了实现IHostedService接口的基类BackgroundService,该类实现如下:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System;
using System.Threading;
using System.Threading.Tasks; namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Base class for implementing a long running <see cref="IHostedService"/>.
/// </summary>
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); /// <summary>
/// This method is called when the <see cref="IHostedService"/> starts. The implementation should return a task that represents
/// the lifetime of the long running operation(s) being performed.
/// </summary>
/// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
/// <returns>A <see cref="Task"/> that represents the long running operations.</returns>
protected abstract Task ExecuteAsync(CancellationToken stoppingToken); /// <summary>
/// Triggered when the application host is ready to start the service.
/// </summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token); // If the task is completed then return it, this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
} // Otherwise it's running
return Task.CompletedTask;
} /// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// </summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
} try
{
// Signal cancellation to the executing method
_stoppingCts.Cancel();
}
finally
{
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
} } public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
}

根据BackgroundService源码,我们只要实现该类的抽象方法ExecuteAsync即可。
可以有两种实现方式来做定时程序,第一种就是实现一个Timer:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks; namespace DemoOne.Models
{
public class TimedBackgroundService : BackgroundService
{
private readonly ILogger _logger;
private Timer _timer; public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
{
_logger = logger;
} protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
_logger.LogInformation("周六!");
return Task.CompletedTask; //Console.WriteLine("MyServiceA is starting."); //stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt")); //while (!stoppingToken.IsCancellationRequested)
//{
// Console.WriteLine("MyServiceA 开始执行"); // await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); // Console.WriteLine("继续执行");
//} //Console.WriteLine("MyServiceA background task is stopping.");
} private void DoWork(object state)
{
_logger.LogInformation($"Hello World! - {DateTime.Now}");
} public override void Dispose()
{
base.Dispose();
_timer?.Dispose();
}
}
}

我们看看StartAsync的源码。上面的实现方式会直接返回一个已完成的Task,这样就会直接运行StartAsync方法的if判断,那么如果我们不走if呢?那么就应该由StartAsync方法返回一个已完成的Task.
第二个即是:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks; namespace DemoOne.Models
{
public class TimedBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("MyServiceA is starting."); stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt")); while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("MyServiceA 开始执行"); await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); Console.WriteLine("继续执行");
} Console.WriteLine("MyServiceA background task is stopping.");
} public override void Dispose()
{
base.Dispose();
}
}
}

最后我们将实现了BackgroundService的类注入到DI即可:
services.AddHostedService<TimedBackgroundService>();
dotnet core的Microsoft.Extensions.Hosting 组件中,充斥着类似IHostedService接口中定义的方法:StartAsync、StopAsync方法。我们注入的HostedService服务会在WebHost类中通过GetRequiredService获取到注入的定时服务。随后执行StartAsync方法开始执行。建议看看Hosting组件源码,会有很多的收获。
aspnet core运行后台服务任务的更多相关文章
- Remote System Explorer Operation总是运行后台服务,卡死eclipse
阿里云 > 教程中心 > android教程 > Remote System Explorer Operation总是运行后台服务,卡死eclipse Remote System E ...
- aspnet core运行后台任务
之前在公司的一个项目中需要用到定时程序,当时使用的是aspnet core提供的IHostedService接口来实现后台定时程序,具体的示例可去官网查看.现在的dotnet core中默认封装了实现 ...
- 【转载】Remote System Explorer Operation总是运行后台服务,卡死eclipse解决办法
原来是eclipse后台进程在远程操作,就是右下角显示的“Remote System Explorer Operation”.折腾了半天,在Stack Overflow找到答案(源地址).把解决方案翻 ...
- Remote System Explorer Operation总是运行后台服务,卡死eclipse解决办法
当你右键编辑控件的id或者其他属性时都会卡很久,发现原来是eclipse后台进程在远程操作,就是右下角显示的“Remote System Explorer Operation”.折腾了半天,在Stac ...
- ASPNETCOREAPI 跨域处理 SQL 语句拼接 多条件分页查询 ASPNET CORE 核心 通过依赖注入(注入服务)
ASPNETCOREAPI 跨域处理 AspNetCoreApi 跨域处理 如果咱们有处理过MV5 跨域问题这个问题也不大. (1)为什么会出现跨域问题: 浏览器安全限制了前端脚本跨站点的访问资源, ...
- 打造跨平台.NET Core后台服务
续之前讲的在TopShelf上部署ASP.NET Core程序,作为后台服务运行,自从.NET Core 3.0出现以后,出现了自带的Generic Host,使得自托管服务变为可能.这种方式和Top ...
- AspNet Core Api Restful +Swagger 发布IIS 实现微服务之旅 (二)
上一步我们创建好CoreApi 接下来在框架中加入 Swagger 并发布 到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore 比 ...
- .NET Core 中的通用主机和后台服务
简介 我们在做项目的时候, 往往要处理一些后台的任务. 一般是两种, 一种是不停的运行,比如消息队列的消费者.另一种是定时任务. 在.NET Framework + Windows环境里, 我们一般会 ...
- ASP.NET Core 6框架揭秘实例演示[21]:如何承载你的后台服务
借助 .NET提供的服务承载(Hosting)系统,我们可以将一个或者多个长时间运行的后台服务寄宿或者承载我们创建的应用中.任何需要在后台长时间运行的操作都可以定义成标准化的服务并利用该系统来承载,A ...
- ASP.NET Core 6框架揭秘实例演示[22]:如何承载你的后台服务[补充]
借助 .NET提供的服务承载(Hosting)系统,我们可以将一个或者多个长时间运行的后台服务寄宿或者承载我们创建的应用中.任何需要在后台长时间运行的操作都可以定义成标准化的服务并利用该系统来承载,A ...
随机推荐
- js es6 delete
前言 首先delete 不同于nodejs delete,看下有什么不同. 正文 var test=5; delete test; console.log(test); 结果是test没有受到任何影响 ...
- 如何将 ASP.NET Core MVC 项目的视图分离到另一个项目
如何将 ASP.NET Core MVC 项目的视图分离到另一个项目 在当下这个年代 SPA 已是主流,人们早已忘记了 MVC 以及 Razor 的故事.但是在某些场景下 SSR 还是有意想不到效果. ...
- JavaWeb技术JSP连接数据库操作
"感谢您阅读本篇博客!如果您觉得本文对您有所帮助或启发,请不吝点赞和分享给更多的朋友.您的支持是我持续创作的动力,也欢迎留言交流,让我们一起探讨技术,共同成长!谢谢!" 0X01 ...
- 2FA(双因素身份验证)之手机令牌(TOTP)逻辑
2FA(双因素身份验证)之手机令牌(TOTP)逻辑 纯猜测,没试过,有空试 分为移动端.客户端以及网页端 Steam那种属于APP是网页,客户端是网页,网页端也是网页,挺抽象的 关键点: 时间一致(时 ...
- 剑指offer21(Java)-调整数组顺序使奇数位于偶数前面(简单)
题目: 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分. 示例: 输入:nums = [1,2,3,4]输出:[1,3,2,4] 注:[ ...
- 力扣119(java)-杨辉三角Ⅱ(简单)
题目: 给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行. 在「杨辉三角」中,每个数是它左上方和右上方的数的和. 示例 1: 输入: rowIndex = 3输出: [1 ...
- 力扣476(java)-数字的补数(简单)
题目: 对整数的二进制表示取反(0 变 1 ,1 变 0)后,再转换为十进制表示,可以得到这个整数的补数. 例如,整数 5 的二进制表示是 "101" ,取反后得到 "0 ...
- Java 应用压测性能问题定位经验分享
简介: 问题千千万,但只要修练了足够深厚的内功,形成一套属于自己的排查问题思路和打法,再加上一套支撑问题排查的工具,凭借已有的经验还有偶发到来的那一丝丝灵感,相信所有的问题都会迎刃而解. 作者:凡勇 ...
- 双11专刊|云原生数据仓库AnalyticDB支撑双11,大幅提升分析实时性和用户体验
简介:2021年双十一刚刚落幕,已连续多年稳定支持双十一大促的云原生数据仓库AnalyticDB,今年双十一期间仍然一如既往的稳定.除了稳定顺滑的基本盘之外,AnalyticDB还有什么亮点呢?下面我 ...
- DataWorks 功能实践速览
简介: DataWorks功能实践系列,帮助您解析业务实现过程中的痛点,提高业务功能使用效率! 功能推荐:独享数据集成资源组 如上期数据同步解决方案介绍,数据集成的批数据同步任务运行时,需要占用一定 ...