Hangfire定时任务无法调度问题求助及相关配置代码
Hangfire 任务无法调度问题排查与解决方案
我遇到了Hangfire Job无法调度的问题,相关截图如下:
恳请提供解决方案。
我的任务代码
var auto = new AutoCallService(dbContext, Configuration, _emailService, _mapper, _hostingEnvironment, _stripeApisService, _logService); //var autoCallService = app.ApplicationServices.GetRequiredService<IAutoCallService>(); //RecurringJob.AddOrUpdate( () => auto.TestJob(), "*/1 * * * *" ); RecurringJob.AddOrUpdate(() => auto.SendInvoiceToUser(), Cron.Hourly); RecurringJob.AddOrUpdate("automatic-change-of-fighters-fighter-class-based-on-fighters-birthday", () => auto.UpdateFightClassForUser(), Cron.MinuteInterval(5),TimeZoneInfo.Utc);
我的Hangfire配置
services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("MSSQL")) ); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new List<IDashboardAuthorizationFilter> { new MyAuthorizationFilter() } }); app.UseHangfireServer();
解决方案建议
依赖注入容器获取服务实例:不要手动
new AutoCallService,这种方式脱离DI容器会导致Hangfire无法管理服务生命周期,甚至引发依赖项初始化异常。改用DI获取实例:var autoCallService = app.ApplicationServices.GetRequiredService<IAutoCallService>(); RecurringJob.AddOrUpdate(() => autoCallService.SendInvoiceToUser(), Cron.Hourly); RecurringJob.AddOrUpdate("automatic-change-of-fighters-fighter-class-based-on-fighters-birthday", () => autoCallService.UpdateFightClassForUser(), Cron.MinuteInterval(5), TimeZoneInfo.Utc);同时确保
AutoCallService已注册到DI容器(比如services.AddScoped<IAutoCallService, AutoCallService>())。调整任务注册时机:确保
UseHangfireServer()执行后再注册定时任务,或者将任务注册放在应用启动完成事件中,避免服务未初始化完成就注册任务:var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>(); lifetime.ApplicationStarted.Register(() => { var autoCallService = app.Services.GetRequiredService<IAutoCallService>(); // 在这里注册定时任务 });验证数据库配置:检查SQL Server连接字符串是否正确,确认应用账号拥有Hangfire表的读写权限。可以手动执行Hangfire初始化脚本,确认
Hangfire.Job、Hangfire.RecurringJob等表结构正常。查看日志排查异常:启用Hangfire日志记录,通过日志定位报错:
services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("MSSQL")) .UseSerilog()); // 适配你的日志框架同时检查应用程序日志,寻找Hangfire相关的错误信息。
检查Dashboard状态:访问
/hangfire面板,查看Recurring Jobs列表是否存在目标任务,状态是否为Enabled。若任务不存在,说明注册流程失败;若存在但未触发,核对Cron表达式和时区设置是否正确。
内容的提问来源于stack exchange,提问作者Ramlakhan Saini
相关产品推荐
相关产品推荐

