找回密码
 立即注册
首页 业界区 安全 .Net6使用Hangfire定时任务

.Net6使用Hangfire定时任务

璋锌 2025-5-30 13:13:12
本文实例环境及版本 .Net6、Hangfire1.8.18、MySql
Hangfire官网地址:https://www.hangfire.io/
Hangfire需使用数据库,请引用对应的
一、基本使用
1、Nuget引用Hangfire
1.png

2.png

 2、在Startup->ConfigureServices中添加
  1. services.AddHangfire(config =>
  2. {
  3.     string conMysqlLocal = Configuration["AppSetting:conMysqlLocal"];
  4.     config.UseStorage(new MySqlStorage(conMysqlLocal, new MySqlStorageOptions
  5.     {
  6.         TablesPrefix = "hangfire", //在数据库中生成表的前缀名
  7.         JobExpirationCheckInterval = TimeSpan.FromHours(1) // Hangfire检查和删除过期任务的频率
  8.     }));
  9.     config.UseFilter(new AutomaticRetryAttribute {
  10.         Attempts=3, //任务失败后最大重试次数
  11.         DelaysInSeconds = new[] { 120, 120 }, // 重试间隔(可选)
  12.     });
  13. });
  14. // 添加Hangfire服务器
  15. services.AddHangfireServer();
复制代码
3、在Startup->Configure中添加
  1. // 配置Hangfire仪表盘(可选)
  2. app.UseHangfireDashboard("/hangfire", new DashboardOptions
  3. {
  4.      DashboardTitle = "任务调度中心",
  5.      Authorization = new[] { new HangfireAuthorizationFilter() }
  6. });
  7. // 几种Hangfire任务方式  循环任务、单次任务、顺序任务等
  8. //1、循环任务  如:每八小时执行一次
  9. //RecurringJob.AddOrUpdate<HangfireTimerService>("每天任务1", x => x.DoTasks(), "0 */8 * * *", new RecurringJobOptions() { TimeZone=TimeZoneInfo.Local});
  10. //2、定时的单次任务  10秒中后执行一次
  11. BackgroundJob.Schedule<HangfireTimerService>(x=>x.DoTasks(),TimeSpan.FromSeconds(10));
  12. //也是定时单次任务  这种类型的任务一般是在应用程序启动的时候执行一次结束后不再重复执行
  13. //BackgroundJob.Enqueue<HangfireTimerService>(x => x.DoTasks());
复制代码
4、可以将子任务封装进HangfireTimerService类中
  1.   public class HangfireTimerService
  2.   {
  3.       /// <summary>
  4.       /// 日志
  5.       /// </summary>
  6.       ILogger<HangfireTimerService> _logger;public HangfireTimerService(ILogger<HangfireTimerService> logger)
  7.       {
  8.           _logger = logger;
  9.       }
  10.       /// <summary>
  11.       /// 此处执行各种定时任务
  12.       /// </summary>
  13.       public void DoTasks()
  14.       {
  15.           _logger.LogWarning("DoTasks 系统任务开始执行!{Time}", DateTime.Now);
  16.           //禁用删除某个任务 根据任务ID
  17.           //RecurringJob.RemoveIfExists("daily-cleanup");
  18.           _logger.LogWarning("DoTasks 系统任务结束了!{Time}", DateTime.Now);
  19.       }
  20.   }
  21.   /// <summary>
  22.   /// 重写Hangfire面板控制权限
  23.   /// </summary>
  24.   public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
  25.   {
  26.       //这里需要配置权限规则
  27.       public bool Authorize(DashboardContext context)
  28.       {
  29.           return true;
  30.       }
  31.   }
复制代码
 
二、其他配置
Hangfire是自带后台的。程序运行后访问后台
访问地址:系统地址/hangfire
 
才疏学浅,相关文档等仅供自我总结,如有相关问题可留言交流谢谢!
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册