hangfire 本地可以正常打开hangfire页面,发布后报401
- 本地可以正常打开hangfire页面,发布后报401
解决办法
增加
CustomAuthorizeFilter
:public class CustomAuthorizeFilter : IDashboardAuthorizationFilter { public bool Authorize([NotNull] DashboardContext context) { return true; } public CustomAuthorizeFilter() { } }
Configure
增加配置,代码也可以其他地方,用下面代码替换原先 app.UseHangfireDashboard() 即可。
:
app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new CustomAuthorizeFilter() } });
- hangfire 关键任务表
select [Key] from [dbo].[Hash] group by [Key];
select * from [dbo].[Set];
二、hangfire使用
1、Nuget下载hangfire。
2、startUp.cs文件代码
Configure中增加
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //配置后台仪表盘 app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new CustomAuthorizeFilter() } }); app.UseHangfireServer();//开始使用Hangfire服务 //定义 每分钟执行 RecurringJob.AddOrUpdate(() => System.Diagnostics.Debugger.Log(1, "", "输出窗口!" + System.DateTime.Now), Cron.Minutely); }
ConfigureServices 中增加
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["ConDb"]; string conn = cs.ConnectionString; services.AddHangfire(x => x.UseSqlServerStorage(conn));
3、注入
4、在打开的Ip:端口号后加上hangfire。显示
注意项:
一、不用打开页面执行任务
很多朋友如果用 Hangfire 把计划任务放在 Controllers控制器的话 可能会造成服务器必须开启 ip/hangfire页面 才能执行计划
对于这个问题 我们用BackgroundService
public class HangfireService : BackgroundService { ISysLogService sysLogService; //这是我测试能否注入我的Service层 public HangfireService(ISysLogService _sysLogService) { sysLogService = _sysLogService; } public override async Task StartAsync(CancellationToken cancellationToken) { RecurringJob.AddOrUpdate("Time_LogTime", () => Console.WriteLine("12"), Cron.MinuteInterval(1)); } protected override Task ExecuteAsync(CancellationToken stoppingToken) { throw new NotImplementedException(); } }
参照:https://blog.huati365.com/5ea90c5b991a04cd
二、不重复执行使用 Mutex
public static Mutex mutex = new Mutex(false); public static void test() { mutex.WaitOne(); intNumber += 1; System.Diagnostics.Debugger.Log(1, "", intNumber + "输出窗口!" + System.DateTime.Now+"\n\r"); Thread.Sleep(TimeSpan.FromSeconds(10)); System.Diagnostics.Debugger.Log(2, "", intNumber + "结束输出窗口!" + System.DateTime.Now + "\n\r"); mutex.ReleaseMutex(); }
代码下载:https://download.csdn.net/download/xbding/74431243