安装包-NuGet
Hangfire.Core
Hangfire.AspNetCore
Hangfire.Dashboard.BasicAuthorization
Hangfire.SqlServer
服务配置
新建一个类 用作service配置
public static class HangfireService
{
public static void AddHangfireService(this IServiceCollection services)
{
// Add Hangfire services.
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage("数据库连接字符串", new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
UsePageLocksOnDequeue = true,
DisableGlobalLocks = true,
//JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔(管理过期记录)。默认值为1小时。
//CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。
}));
// Add the processing server as IHostedService
services.AddHangfireServer();
}
}
StartUp中添加服务
services.AddHangfireService();
数据面板配置
新建一个类 进行配置
public static class HangfireMiddleware
{
public static void UseHangfireMiddleware(this IApplicationBuilder app)
{
if (app == null) throw new ArgumentNullException(nameof(app));
app.UseHangfireServer(ConfigureOptions());//配置服务
app.UseHangfireDashboard(AppsettingConfig.HangfirePathMatch, HfAuthor());//配置面板
//backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
//backgroundJobs.AddOrUpdate();
HangfireService();//配置各个任务
}
/// <summary>
/// 配置账号模板信息
/// </summary>
/// <returns></returns>
public static DashboardOptions HfAuthor()
{
var filter = new BasicAuthAuthorizationFilter(
new BasicAuthAuthorizationFilterOptions
{
SslRedirect = false,
RequireSsl = false,
LoginCaseSensitive = false,
Users = new[]
{
new BasicAuthAuthorizationUser
{
Login = 账号, //可视化的登陆账号
PasswordClear = 密码 //可视化的密码
}
}
});
return new DashboardOptions
{
Authorization = new[] { filter }
};
}
/// <summary>
/// 配置启动
/// </summary>
/// <returns></returns>
public static BackgroundJobServerOptions ConfigureOptions()
{
return new BackgroundJobServerOptions
{
Queues = new[] { HangfireConfigureQueue.Myqueue, HangfireConfigureQueue.Default },//队列名称,只能为小写
WorkerCount = Environment.ProcessorCount * 5, //并发任务
ServerName = AppsettingConfig.HangfireServerName, //代表服务名称
};
}
#region 配置服务
public static void HangfireService()
{
//这里呢就是需要触发的方法 "0/10 * * * * ? " 可以自行搜索cron表达式 代表循环的规律很简单
//GameLenthPush代表你要触发的类 UserGameLenthPush代表你要触发的方法
//RecurringJob.AddOrUpdate<GameLenthPush>(s => s.UserGameLenthPush(), "0/10 * * * * ? ", TimeZoneInfo.Local);
//RecurringJob.AddOrUpdate<ITestServices>(s => s.TestHangfiredefault(), "0/5 * * * * ? ", TimeZoneInfo.Local);
//RecurringJob.AddOrUpdate<ITestServices>(s => s.TestHangfireMyqueue(), "0/5 * * * * ? ", TimeZoneInfo.Local, HangfireConfigureQueue.Myqueue);
}
#endregion
}
添加服务面板
// 使用Hangfire
app.UseHangfireMiddleware();