.Net 6使用Hangfire(一)

本文仅描述.net 6环境下如何安装和使用Hangfire进行后台作业任务调度。

1、首先安装需要的Nuget包:

Hangfire.AspNetCore

如果有持久化需求的话,还需要安装其它包,hangfire支持存储在SQLserverredismemory中,

本文演示使用的是SQLserver数据库,需要先在数据库中创建名为HangfireTest的数据库,然后配置连接字符串

 

2、注入Hangfire相关的服务

 1  public static IServiceCollection ConfigHangfire(this IServiceCollection services, IConfiguration configuration)
 2     {
 3       //注册Hangfir配置
 4       services.AddHangfire(config =>
 5       {
 6         config.UseSerilogLogProvider();   //设置使用serilog来记录相关日志 可以更换其他
 7         config.SetDataCompatibilityLevel(CompatibilityLevel.Version_180);
 8         config.UseSimpleAssemblyNameTypeSerializer();
 9         config.UseRecommendedSerializerSettings();
10         config.UseFilter(new LogHangfireFailureAttribute());  //使用过滤器,当失败重试次数达到最大时记录日志
11         config.UseFilter(new LogHangfirePerformAttribute());  //使用过滤器,当作业执行时触发
12         //config.UseMemoryStorage();  //使用本地内存来存储相关数据,也可更换redis和SQL
13         config.UseSqlServerStorage(configuration.GetConnectionString("HangfireConnection"))
14         .WithJobExpirationTimeout(TimeSpan.FromDays(1));  //设置使用SQL数据库来存储数据,并且设置过期时间(默认最少为24小时) 必须跟在UseXXXStorage后使用
15       });
16       // Add the processing server as IHostedService
17       services.AddHangfireServer();
18       //注册自定义的后台作业
19       services.AddTransient<IHangfireJob, HelloHangfireJob>();
20 
21       return services;
22     }
 1  public static IApplicationBuilder UseHangfire(this IApplicationBuilder app, IWebHostEnvironment environment)
 2     {
 3       //判断是否开发环境
 4       if (environment.IsDevelopment())
 5       {
 6         //启用hangfire仪表盘管理功能
 7         app.UseHangfireDashboard("/hangfire", new DashboardOptions
 8         {
 9           DashboardTitle = "Hangfire Dashboard Manage", //页面标题
10           AppPath = "http://localhost:5249/swagger",
11           //IsReadOnlyFunc = context => true  //设置控制面板仅用于预览
12         });
13       }
14       //var jobId = BackgroundJob.Enqueue(() => Debug.WriteLine("fire-and-forgot job start"));
15       //BackgroundJob.ContinueJobWith(jobId, () => Debug.WriteLine("continue job start"));
16 
17       //注册后台启动的作业
18       using (var scope = app.ApplicationServices.CreateScope())
19       {
20         var helloHangfireJob = scope.ServiceProvider.GetRequiredService<IHangfireJob>();
21         BackgroundJob.Schedule(() => helloHangfireJob.RunSendEmailJob(), TimeSpan.FromMinutes(1));
22         RecurringJob.AddOrUpdate("closeUnPayOrder", () => helloHangfireJob.RunCloseUnpayOrder(), Cron.Minutely(), new RecurringJobOptions
23         {
24           //TimeZone = TimeZoneInfo.Local
25         });
26       }
27       return app;
28     }
        //注册HangFire相关服务
        builder.Services.ConfigHangfire(builder.Configuration);
        //启用hangfire中间件
        app.UseHangfire(app.Environment);

3、使用

 1   public interface IHangfireJob
 2   {
 3     public Task RunSendEmailJob();
 4 
 5     public Task RunCloseUnpayOrder();
 6   }
 7 
 8   public class HelloHangfireJob : IHangfireJob
 9   {
10     private readonly IEmailHelper _emailHelper;
11 
12     public HelloHangfireJob(IEmailHelper emailHelper)
13     {
14       _emailHelper = emailHelper;
15     }
16 
17     [LogHangfireFailure]
18     public Task RunCloseUnpayOrder()
19     {
20       //从数据库获取未支付已过期的订单数据
21       Console.WriteLine($"{DateTime.Now} 处理未支付已过期的订单");
22 
23       return Task.CompletedTask;
24     }
25 
26     [LogHangfireFailure]
27     [LogHangfirePerform]
28     public async Task RunSendEmailJob()
29     {
30       await _emailHelper.Send(new EmailData("96@qq.com", "zjj", "templateCode", new List<string> { "zjj@gmail.com" }, "测试发送邮件", "测试测试", EmailType.QQ));
31     }
32   }
1     [HttpGet]
2     public ApiResult TestHangfire()
3     {
4       var jobId = BackgroundJob.Enqueue(() => Debug.WriteLine("fire-and-forgot job start"));
5       BackgroundJob.ContinueJobWith(jobId, () => Debug.WriteLine("continue job start"));
6       BackgroundJob.Schedule(() => Debug.WriteLine("delay job start"), TimeSpan.FromMinutes(1));
7       return new Success();
8     }

 运行效果演示:

浏览器中查看仪表盘页面:

 查看数据库表,可以看到有数据了

 

引用资料:

Configuration — Hangfire Documentation

 

posted @ 2023-05-06 11:12  开心的菜鸟程序猿  阅读(842)  评论(0编辑  收藏  举报