.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. ...
随机推荐
- SpringBoot使用JdbcTemplate批量保存
@Autowired DataSourceProperties dataSourceProperties; @Autowired ApplicationContext applicationConte ...
- OGNL(Object-Graph Navigation Language)使用
OGNL表达式:https://www.jianshu.com/p/6bc6752d11f4 Apache OGNL:http://commons.apache.org/proper/commons- ...
- springboot项目中的日志输出
#修改默认输出级别,trace < debug < info < warn < errorlogging.level.com.lagou=trace#控制台输出logging. ...
- Spring系列28:@Transactional事务源码分析
本文内容 @Transactional事务使用 @EnableTransactionManagement 详解 @Transactional事务属性的解析 TransactionInterceptor ...
- ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory")
/etc/init.d/mysql startmysql 没有启动参考 https://blog.csdn.net/sirobot/
- 8_LQR 控制器_状态空间系统Matlab/Simulink建模分析
再线性控制器中讲到: 举例说明(线性控制器中的一个例子)博客中有说明 在matlab中:使用lqr求解K1.K2 这里希望角度(即x1)能迅速变化,所以Q矩阵中Q11为100,并没有关心角速度(dot ...
- PC端操作系统、移动端操作系统、嵌入式操作系统
左侧部分已是历史的操作系统,右侧的还是活跃的操作系统.安卓系统Android 是Google开发的基于Linux平台的开源手机操作系统.它包括操作系统.用户界面和应用程序-- 移动电话工作所需的全部软 ...
- 使用el-tree-transfer的方式
1.首先在组件中引入el-tree-transfer 2.然后在template中使用注册后的组件 参数:title 说明:标题 类型:Array 必填:false 默认:["源列表&quo ...
- 无需Flash实现图片裁剪——HTML5中级进阶
前言 图片裁剪上传,不仅是一个很贴合用户体验的功能,还能够统一特定图片尺寸,优化网站排版,一箭双雕. 需求就是那么简单,在浏览器里裁剪图片并上传到服务器. 我第一个想到的方法就是,将图片和裁剪参数(x ...
- 探讨:微信小程序应该如何设计
微信小程序公测后,开发者非常热情,都有很高的期待,都想抓住这一波红利.但是热情背后需要冷静,我们需要搞清楚两个问题: 微信想要我们做什么?微信小程序可以做什么? 微信想要我们做什么? 首先来弄清楚微信 ...
