在asp.net项目使用Hangfire框架作为定时执行任务
Hangfire框架是.net平台的一个轻量任务调度框架。使用非常方便。由于我的项目是老项目,某种原因没法升级.net版本,还是使用.net framework 4.0版本,使用VS2010进行开发,VS2010不支持.net framework 4.+版本。但是呢,Hangfire支持.NET Framework 4.5或更高版本 ,因此,索性开发工具也由VS2010升级到了VS2022最新版本。
更改项目目标框架支持.NET Framework 4.8。

并把所有类库都更改为.NET Framework 4.8版本。
这样,我们就可以在asp.net应用程序中使用Hangfire框架了。
首先,在程序包管理器控制台输入下面命令:
Install-Package Hangfire.Core Install-Package Hangfire.SqlServer Install-Package Hangfire.AspNet
其次,asp.net项目,OWIN Startup类旨在将Web应用程序引导逻辑保留在一个位置。在VS2022中,在项目右键单击项目》添加》OWIN Startup Class菜单选项,来添加一个Startup类。

这样,在项目就新建了一个Startup.cs文件。
然后,配置Hangfire数据库连接。
<connectionStrings>
<add name="HangFireConnection" connectionString="Data Source=127.0.0.1;Initial Catalog=HangFireTest;user id=sa;password=123456" providerName="System.Data.SqlClient" />
</connectionStrings>
配置Hangfire Dashboard仪表盘访问过滤器,新建HangfireAuthorizationFilter.cs类。我们可以直接在Startup.cs新建一个类。
// 自定义HangFire仪表盘访问权限 public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize([NotNull] DashboardContext context) { //var owinContext = new OwinContext(context.GetOwinEnvironment()); //return owinContext.Authentication.User.Identity.IsAuthenticated; //直接返回true 允许所有人可以访问 return true; } }
这里,为了方便,运行所有人可以访问。具体自己的生产项目,可以对其配置相应的权限授权,限制一些人访问。
最后,配置Startup.cs类,代码如下:
using Hangfire; using Hangfire.Annotations; using Hangfire.Dashboard; using Hangfire.SqlServer; using Microsoft.Owin; using Owin; using Service; using System; using System.Collections.Generic; [assembly: OwinStartup(typeof(Web.Startup))] namespace Web { public class Startup { public void Configuration(IAppBuilder app) { app.UseHangfireAspNet(GetHangfireServers); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangfireAuthorizationFilter() },//默认情况下,只允许对Hangfire Dashboard进行本地访问。必须配置仪表板授权才能允许远程访问。 IsReadOnlyFunc = (Hangfire.Dashboard.DashboardContext context) => true //只读模式 }); // HangFire 任务启动 BackgroundJob.Enqueue(() => System.Diagnostics.Debug.WriteLine("Hello world from Hangfire!")); for (int i = 0; i < 100; i++) { var jobId = BackgroundJob.Schedule( () => System.Diagnostics.Debug.WriteLine("Hello world from Schedule."), TimeSpan.FromSeconds(i)); } } private IEnumerable<IDisposable> GetHangfireServers() { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HangFireConnection"].ConnectionString; GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(connectionString, new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true }); yield return new BackgroundJobServer(); } } // 自定义HangFire仪表盘访问权限 public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize([NotNull] DashboardContext context) { //var owinContext = new OwinContext(context.GetOwinEnvironment()); //return owinContext.Authentication.User.Identity.IsAuthenticated; //直接返回true 允许所有人可以访问 return true; } } }
然后,启动网站调试。
下面是Hangfire仪表盘截图。


浙公网安备 33010602011771号