.NetCore Hangfire任务计划
安装Hangfire
新建ASP.NET Core空 项目,.Net Core版本3.1

往*.csproj添加包引用,添加新的PackageReference标记。如下所示。请注意,下面代码段中的版本可能已经过时,如有需要,请使用nuget获取最新版本。
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Hangfire.Core" Version="1.7.28" />
<PackageReference Include="Hangfire.SqlServer" Version="1.7.28" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.7.28" />
</ItemGroup>
创建数据库
从上面的代码片段中可以看到,在本文中,我们将使用SQL Server作为作业存储。在配置Hangfire之前,您需要为它创建一个数据库,或者使用现有的数据库。下面的配置字符串指向本地计算机上SQLEXPRESS实例中的HangfireTest数据库。
您可以使用SQLServerManagementStudio或任何其他方式执行以下SQL命令。如果您使用的是其他数据库名称或实例,请确保在接下来的步骤中配置Hangfire时更改了连接字符串。
CREATE DATABASE [HangfireTest]
GO
配置Settings
下面将定义HangfireConnection连接来进行表迁移,同时AspNetCore包与ASP进行了日志记录集成.NET核心应用程序。Hangfire的日志信息有时非常重要,有助于诊断不同的问题。信息级别允许查看Hangfire的工作情况,警告和更高的日志级别有助于调查问题,建议调整日志级别
{
"ConnectionStrings": {
"HangfireConnection": "Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;"
},
"Logging": {
"LogLevel": {
"Default": "Warning",
"Hangfire": "Information"
}
}
}
更新应用程序设置后,打开Startup.cs文件。startup类是ASP的核心。NET核心应用程序的配置。首先,我们需要导入Hangfire名称空间,由于建的是空项目,所以需要导入Configuration
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Hangfire;
using Hangfire.SqlServer;
注册服务
使用asp.netcore内置DI注入Hangfire服务
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Add Hangfire services.
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
})); // Add the processing server as IHostedService
services.AddHangfireServer();
}
添加Hangfire面板
如果只是作为后台作业,也可不使用面板功能,按需添加
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapHangfireDashboard();
});
BackgroundJob.Enqueue(() => Console.WriteLine("测试"));
}
运行程序
生成数据表

访问http://localhost:5000/hangfire
添加Hangfire面板授权
新建MyAuthorizationFilter.cs
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
string header = httpContext.Request.Headers["Authorization"];//获取授权
if(header == null)
return AuthenicateLogin();
//解析授权
var authHeader = AuthenticationHeaderValue.Parse(header);
var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
var username = credentials[0];
var password = credentials[1];
//验证登录
if (username == "admin" && password =="123456")
return true;
else
return AuthenicateLogin();
//跳转简单登录界面
bool AuthenicateLogin()
{
httpContext.Response.StatusCode = 401;
httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\"");
context.Response.WriteAsync("Authenticatoin is required.");
return false;
} }
}
Hangfire面板修改
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); app.UseEndpoints(endpoints =>
{
endpoints.MapHangfireDashboard(new DashboardOptions
{
Authorization = new[] { new MyAuthorizationFilter() }
});
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
BackgroundJob.Enqueue(() => Console.WriteLine("测试"));
}
运行程序
.NetCore Hangfire任务计划的更多相关文章
- 新生命团队netcore服务器免费开放计划
为了便于大家学习测试netcore,我们计划提供1~3台公网Linux服务器(CentOS/Ubuntu),1vCPU+1G内存+100Mbps,为期1年,每周重置系统修改一次密码.对使用者要求如下: ...
- 一系列令人敬畏的.NET核心库,工具,框架和软件
内容 一般 框架,库和工具 API 应用框架 应用模板 身份验证和授权 Blockchain 博特 构建自动化 捆绑和缩小 高速缓存 CMS 代码分析和指标 压缩 编译器,管道工和语言 加密 数据库 ...
- Soa: 一个轻量级的微服务库
Soa 项目地址:Github:MatoApps/Soa 介绍 一个轻量级的微服务库,基于.Net 6 + Abp框架 可快速地将现有项目改造成为面向服务体系结构,实现模块间松耦合. 感谢 Rabbi ...
- 【netcore基础】.Net core自动作业之Hangfire
nuget搜索:Hangfire 安装即可,这里我选择的是 1.7.0-beta1 版本 我是用这个集成到了 mvc api里 这里需要在 Startup 文件里进行如下配置 在配置方法 Config ...
- 在.netcore webapi项目中使用后台任务工具Hangfire
安装Hangfire 在webapi项目中通过nuget安装Hangfire.Core,Hangfire.SqlServer,Hangfire.AspNetCore,截止到目前的最新版本是1.7.6. ...
- asp.net core计划任务探索之hangfire+redis+cluster
研究了一整天的quartz.net,发现一直无法解决cluster模式下多个node独立运行的问题,改了很多配置项,仍然是每个node各自为战.本来cluster模式下的各个node应该是负载均衡的, ...
- .netcore简单使用hangfire
Hangfire简介 Hangfire是一个开源的任务调度框架,它内置集成了控制页面,很方便我们查看,控制作业的运行:对于运行失败的作业自动重试运行.它支持永久性存储,支持存储于mssql,mysql ...
- HangFire快速入门 分布式后端作业调度框架服务
安装 NuGet 上有几个可用的Hangfire 的软件包.如果在ASP.NET应用程序中安装HangFire,并使用Sql Server作为存储器,那么请在Package Manager Conso ...
- C# NetCore使用AngleSharp爬取周公解梦数据
这一章详细讲解编码过程 那么接下来就是码代码了,GO 新建NetCore WebApi项目 空的就可以 NuGet安装 Install-Package AngleSharp 或者界面安装 using. ...
随机推荐
- python模块相互依赖的解决方案
第一种:将相互依赖的文件中的其中一个文件的代码移植到另一个文件中... 第二种:将 import .... 或 from ... import 语句的位置移动到def函数内部,由于import和fro ...
- PACT 在微服务架构中的用途是什么?
PACT 是一个开源工具,允许测试服务提供者和消费者之间的交互,与合同隔离, 从而提高微服务集成的可靠性. 微服务中的用法 用于在微服务中实现消费者驱动的合同. 测试微服务的消费者和提供者之间的消费者 ...
- 数据结构:DHU顺序表ADT模板设计及简单应用:找匹配
顺序表ADT模板设计及简单应用:找匹配 时间限制: 1S类别: DS:线性表->线性表应用 问题描述: 输入范例: 100000100000 99999 99998 99997 99996 99 ...
- mysql学习 | LeetCode数据库简单查询练习
力扣:https://leetcode-cn.com/ 力扣网数据库练习:https://leetcode-cn.com/problemset/database/ 文章目录 175. 组合两个表 题解 ...
- 论文解读( N2N)《Node Representation Learning in Graph via Node-to-Neighbourhood Mutual Information Maximization》
论文信息 论文标题:Node Representation Learning in Graph via Node-to-Neighbourhood Mutual Information Maximiz ...
- React+dva+webpack+antd-mobile 实战分享(二)
第一篇 https://segmentfault.com/a/11... 在上一篇文章中教给大家了怎么搭建项目的架子:那么今天我们就来说一下项目里的导航和列表的实现 导航 废话不说啦 下面直接给大家讲 ...
- Codepen 每日精选(2018-4-11)
按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以打开原始页面. 纯 css 写行走的大象https://codepen.io/FabioG/ful... 纯 css 画的 ...
- 【Android开发】监听图库数据库的变化
步骤一: 保存图片或者删除之前,初始化ContentObserver ScreenshotContentObserver mScreenObserver = new ScreenshotContent ...
- Ubuntu安装docker-compose(摘自官网,自用)
安装 Docker Compose 预计阅读时间:8分钟 加速 Docker 桌面中的新功能 Docker Desktop 可帮助您在 Mac 和 Windows 上轻松构建.共享和运行容器,就像在 ...
- 【深度学习 论文篇 01-1 】AlexNet论文翻译
前言:本文是我对照原论文逐字逐句翻译而来,英文水平有限,不影响阅读即可.翻译论文的确能很大程度加深我们对文章的理解,但太过耗时,不建议采用.我翻译的另一个目的就是想重拾英文,所以就硬着头皮啃了.本文只 ...
