安装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任务计划的更多相关文章

  1. 新生命团队netcore服务器免费开放计划

    为了便于大家学习测试netcore,我们计划提供1~3台公网Linux服务器(CentOS/Ubuntu),1vCPU+1G内存+100Mbps,为期1年,每周重置系统修改一次密码.对使用者要求如下: ...

  2. 一系列令人敬畏的.NET核心库,工具,框架和软件

    内容 一般 框架,库和工具 API 应用框架 应用模板 身份验证和授权 Blockchain 博特 构建自动化 捆绑和缩小 高速缓存 CMS 代码分析和指标 压缩 编译器,管道工和语言 加密 数据库 ...

  3. Soa: 一个轻量级的微服务库

    Soa 项目地址:Github:MatoApps/Soa 介绍 一个轻量级的微服务库,基于.Net 6 + Abp框架 可快速地将现有项目改造成为面向服务体系结构,实现模块间松耦合. 感谢 Rabbi ...

  4. 【netcore基础】.Net core自动作业之Hangfire

    nuget搜索:Hangfire 安装即可,这里我选择的是 1.7.0-beta1 版本 我是用这个集成到了 mvc api里 这里需要在 Startup 文件里进行如下配置 在配置方法 Config ...

  5. 在.netcore webapi项目中使用后台任务工具Hangfire

    安装Hangfire 在webapi项目中通过nuget安装Hangfire.Core,Hangfire.SqlServer,Hangfire.AspNetCore,截止到目前的最新版本是1.7.6. ...

  6. asp.net core计划任务探索之hangfire+redis+cluster

    研究了一整天的quartz.net,发现一直无法解决cluster模式下多个node独立运行的问题,改了很多配置项,仍然是每个node各自为战.本来cluster模式下的各个node应该是负载均衡的, ...

  7. .netcore简单使用hangfire

    Hangfire简介 Hangfire是一个开源的任务调度框架,它内置集成了控制页面,很方便我们查看,控制作业的运行:对于运行失败的作业自动重试运行.它支持永久性存储,支持存储于mssql,mysql ...

  8. HangFire快速入门 分布式后端作业调度框架服务

    安装 NuGet 上有几个可用的Hangfire 的软件包.如果在ASP.NET应用程序中安装HangFire,并使用Sql Server作为存储器,那么请在Package Manager Conso ...

  9. C# NetCore使用AngleSharp爬取周公解梦数据

    这一章详细讲解编码过程 那么接下来就是码代码了,GO 新建NetCore WebApi项目 空的就可以 NuGet安装 Install-Package AngleSharp 或者界面安装 using. ...

随机推荐

  1. yarn上运行flink环境搭建

    主要完成hadoop集群搭建和yarn上运行flink 1.搭建hadoop伪集群 主要是搭建hadoop MapReduce(yarn)和HDFS 1.1 下载&配置环境变量 这里下载的ha ...

  2. AOP 有哪些实现方式?

    实现 AOP 的技术,主要分为两大类: 静态代理 指使用 AOP 框架提供的命令进行编译,从而在编译阶段就可生成 AOP 代理类, 因此也称为编译时增强: 编译时编织(特殊编译器实现) 类加载时编织( ...

  3. int 和 Integer 哪个会占用更多的内存?

    Integer 对象会占用更多的内存.Integer 是一个对象,需要存储对象的元数据. 但是 int 是一个原始类型的数据,所以占用的空间更少.

  4. Spring配置连接池和 Dao 层使用 jdbcTemplate

    1.Spring 配置 c3p0 连接池 (1)导入jar包(Maven项目) <dependency> <groupId>com.mchange</groupId> ...

  5. Python - 字符串基础知识

  6. 设计一个简单的devops系统

    前言 公司设计的RDMS挺好用的,我也照猫画虎简单的设计一个DevOps系统,与大家分享,不足之处欢迎拍砖,以免误人子弟 前置条件 gitlab gitlab-runner k8s 1. gitlab ...

  7. .NET 6学习笔记(3)——在Windows Service中托管ASP.NET Core并指定端口

    在上一篇<.NET 6学习笔记(2)--通过Worker Service创建Windows Service>中,我们讨论了.NET Core 3.1或更新版本如何创建Windows Ser ...

  8. BMZCTF ssrfme

    <?php if(isset($_GET) && !empty($_GET)){ $url = $_GET['file']; $path = "upload/" ...

  9. glusterfs架构和原理

    分布式存储已经研究很多年,但直到近年来,伴随着谷歌.亚马逊和阿里等互联网公司云计算和大数据应用的兴起,它才大规模应用到工程实践中.如谷歌的分布式文件系统GFS.分布式表格系统google Bigtab ...

  10. matlab拟合函数的三种方法

    方法一:多项式拟合polyfit 1 x=[1 2 3 4 5 6 7 8 9]; 2 3 y=[9 7 6 3 -1 2 5 7 20]; 4 P= polyfit(x, y, 3) %三阶多项式拟 ...