.Net6使用Hangfire定时任务

本文实例环境及版本 .Net6、Hangfire1.8.18、MySql

Hangfire官网地址:https://www.hangfire.io/

Hangfire需使用数据库,请引用对应的

一、基本使用

1、Nuget引用Hangfire

 2、在Startup->ConfigureServices中添加

services.AddHangfire(config =>
{
    string conMysqlLocal = Configuration["AppSetting:conMysqlLocal"];
    config.UseStorage(new MySqlStorage(conMysqlLocal, new MySqlStorageOptions
    {
        TablesPrefix = "hangfire", //在数据库中生成表的前缀名
        JobExpirationCheckInterval = TimeSpan.FromHours(1) // Hangfire检查和删除过期任务的频率
    }));
    config.UseFilter(new AutomaticRetryAttribute { 
        Attempts=3, //任务失败后最大重试次数
        DelaysInSeconds = new[] { 120, 120 }, // 重试间隔(可选)
    });
});
// 添加Hangfire服务器
services.AddHangfireServer();

3、在Startup->Configure中添加

 // 配置Hangfire仪表盘(可选)
 app.UseHangfireDashboard("/hangfire", new DashboardOptions
 {
     DashboardTitle = "任务调度中心",
     Authorization = new[] { new HangfireAuthorizationFilter() }
 });

 // 几种Hangfire任务方式  循环任务、单次任务、顺序任务等
 //1、循环任务  如:每八小时执行一次
 //RecurringJob.AddOrUpdate<HangfireTimerService>("每天任务1", x => x.DoTasks(), "0 */8 * * *", new RecurringJobOptions() { TimeZone=TimeZoneInfo.Local});

 //2、定时的单次任务  10秒中后执行一次
 BackgroundJob.Schedule<HangfireTimerService>(x=>x.DoTasks(),TimeSpan.FromSeconds(10));
 //也是定时单次任务  这种类型的任务一般是在应用程序启动的时候执行一次结束后不再重复执行
 //BackgroundJob.Enqueue<HangfireTimerService>(x => x.DoTasks());

4、可以将子任务封装进HangfireTimerService类中

  public class HangfireTimerService
  {
      /// <summary>
      /// 日志
      /// </summary>
      ILogger<HangfireTimerService> _logger;public HangfireTimerService(ILogger<HangfireTimerService> logger)
      {
          _logger = logger;
      }

      /// <summary>
      /// 此处执行各种定时任务
      /// </summary>
      public void DoTasks()
      {
          _logger.LogWarning("DoTasks 系统任务开始执行!{Time}", DateTime.Now);
          //禁用删除某个任务 根据任务ID
          //RecurringJob.RemoveIfExists("daily-cleanup");

          _logger.LogWarning("DoTasks 系统任务结束了!{Time}", DateTime.Now);
      }
  }

  /// <summary>
  /// 重写Hangfire面板控制权限
  /// </summary>
  public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
  {
      //这里需要配置权限规则
      public bool Authorize(DashboardContext context)
      {
          return true;
      }
  }

 

二、其他配置

Hangfire是自带后台的。程序运行后访问后台

访问地址:系统地址/hangfire

 

才疏学浅,相关文档等仅供自我总结,如有相关问题可留言交流谢谢!

 

posted @ 2025-05-16 09:46  独角马  阅读(127)  评论(0)    收藏  举报