.NET Core中如何设置Hangfire定时任务计划?

2026-05-06 05:111阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计641个文字,预计阅读时间需要3分钟。

.NET Core中如何设置Hangfire定时任务计划?

安装Hangfire,新建ASP.NET Core项目,.NET Core版本3.1,在*.csproj文件中添加包引用和新的PackageReference标记。

plaintext安装Hangfire,创建新的ASP.NET Core项目,版本3.1,在项目文件中添加以下内容:

安装Hangfire

新建ASP.NET Core空 项目,.Net Core版本3.1

往*.csproj添加包引用,添加新的PackageReference标记。如下所示。请注意,下面代码段中的版本可能已经过时,如有需要,请使用nuget获取最新版本。

<ItemGroup> <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与Hangfire进行了日志记录集成。Hangfire的日志信息有时非常重要,有助于诊断不同的问题。信息级别允许查看Hangfire的工作情况,警告和更高的日志级别有助于调查问题,建议调整日志级别

{ "ConnectionStrings": { "HangfireConnection": "Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;" }, "Logging": { "LogLevel": { "Default": "Warning", "Hangfire": "Information" } } }

更新应用程序设置后,打开Startup.cs文件。startup类是.NET CORE应用程序的配置。首先,我们需要导入Hangfire名称空间,由于建的是空项目,所以还需要导入Configuration.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration; using Hangfire; using Hangfire.SqlServer; 注册服务

使用asp.netcore内置DI注入Hangfire服务

.NET Core中如何设置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("测试"));

} 运行程序

生成数据表

访问localhost:5000/hangfire

添加Hangfire面板授权

新建MyAuthorizationFilter.cs

public class MyAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize(DashboardContext context) { var docs.hangfire.io/en/latest/getting-started/index.html

本文共计641个文字,预计阅读时间需要3分钟。

.NET Core中如何设置Hangfire定时任务计划?

安装Hangfire,新建ASP.NET Core项目,.NET Core版本3.1,在*.csproj文件中添加包引用和新的PackageReference标记。

plaintext安装Hangfire,创建新的ASP.NET Core项目,版本3.1,在项目文件中添加以下内容:

安装Hangfire

新建ASP.NET Core空 项目,.Net Core版本3.1

往*.csproj添加包引用,添加新的PackageReference标记。如下所示。请注意,下面代码段中的版本可能已经过时,如有需要,请使用nuget获取最新版本。

<ItemGroup> <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与Hangfire进行了日志记录集成。Hangfire的日志信息有时非常重要,有助于诊断不同的问题。信息级别允许查看Hangfire的工作情况,警告和更高的日志级别有助于调查问题,建议调整日志级别

{ "ConnectionStrings": { "HangfireConnection": "Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;" }, "Logging": { "LogLevel": { "Default": "Warning", "Hangfire": "Information" } } }

更新应用程序设置后,打开Startup.cs文件。startup类是.NET CORE应用程序的配置。首先,我们需要导入Hangfire名称空间,由于建的是空项目,所以还需要导入Configuration.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration; using Hangfire; using Hangfire.SqlServer; 注册服务

使用asp.netcore内置DI注入Hangfire服务

.NET Core中如何设置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("测试"));

} 运行程序

生成数据表

访问localhost:5000/hangfire

添加Hangfire面板授权

新建MyAuthorizationFilter.cs

public class MyAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize(DashboardContext context) { var docs.hangfire.io/en/latest/getting-started/index.html