1.使用nuget添加hangfire
startup.cs中的引用
using Hangfire;
using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.MySql.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Data;
startup.cs
增加如下代码
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
string s = Configuration["DBConnStr:MySQL:ConnectionString"];
services.AddDbContext<EFCoreContext>(options => options.UseMySql(Configuration["DBConnStr:MySQL:ConnectionString"]));
services.AddHangfire(x => x.UseStorage(new MySqlStorage(
Configuration["DBConnStr:Hangfire:ConnectionString"],
new MySqlStorageOptions
{
TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事务隔离级别。默认是读取已提交。
QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。
JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔(管理过期记录)。默认值为1小时。
CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。
PrepareSchemaIfNecessary = true, //- 如果设置为true,则创建数据库表。默认是true。
DashboardJobListLimit = 50000, //- 仪表板作业列表限制。默认值为50000。
TransactionTimeout = TimeSpan.FromMinutes(1), //- 交易超时。默认为1分钟。
TablePrefix = "Hangfire" //- 数据库中表的前缀。默认为none
}
)));
services.AddMvc();
}
继续增加hangfire访问路径
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
//配置hangfire访问路径
app.UseHangfireServer();
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[]
{
new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
{
SslRedirect = false, // 是否将所有非SSL请求重定向到SSL URL
RequireSsl = false, // 需要SSL连接才能访问HangFire Dahsboard。强烈建议在使用基本身份验证时使用SSL
LoginCaseSensitive = false, //登录检查是否区分大小写
Users = new[] //配置登陆账号和密码
{
new BasicAuthAuthorizationUser
{
Login ="admin",//用户名
PasswordClear="123456"
}
}
})
}
});
}
运行程序,在地址后面加入/hangfire 即可看到下图
注意appsettings.json 文件中mysql连接字符串需要加入Allow User Variables=true否则会报错
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"DBConnStr": {
"Redis": {
"ConnectionString": "localhost:6379,password=123456,abortConnect=false",
"Db": 10
},
"MySQL": {
"ConnectionString": "server=192.168.1.3;port=3306;database=a;uid=root;pwd=123456;CharSet=utf8;pooling=true;SslMode=None;"
},
"Hangfire": {
"ConnectionString": "server=192.168.1.8;port=3306;database=Hangfire;uid=root;pwd=123456;CharSet=utf8;pooling=true;SslMode=None;Allow User Variables=true"
},
"WorkerId": 1 // 0-31
},
"AllowedHosts": "*"
}
使用方法示例
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseHangfireServer();
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate(() => TestAsync(), Cron.Minutely());
}
public static async Task TestAsync()
{
// to do...
}