使用Hangfire+.NET 6实现定时任务管理
发布时间:2023-02-17 10:08:06 所属栏目:asp.Net 来源:互联网
导读:在.NET开发生态中,我们以前开发定时任务都是用的Quartz.NET完成的。在这篇文章里,记录一下另一个很强大的定时任务框架的使用方法:Hangfire。两个框架各自都有特色和优势,可以根据参考文章里张队的那篇文章对两个框架的对比来进行选择。 引入Nuget包和配
在.NET开发生态中,我们以前开发定时任务都是用的Quartz.NET完成的。在这篇文章里,记录一下另一个很强大的定时任务框架的使用方法:Hangfire。两个框架各自都有特色和优势,可以根据参考文章里张队的那篇文章对两个框架的对比来进行选择。 引入Nuget包和配置 引入Hangfire相关的Nuget包: Hangfire.AspNetCore Hangfire.MemoryStorage Hangfire.Dashboard.Basic.Authentication 并对Hangfire进行服务配置: builder.Services.AddHangfire(c => { // 使用内存数据库演示,在实际使用中,会配置对应数据库连接,要保证该数据库要存在 c.UseMemoryStorage(); }); // Hangfire全局配置 GlobalConfiguration.Configuration .UseColouredConsoleLogProvider() .UseSerilogLogProvider() .UseMemoryStorage() .WithJobExpirationTimeout(TimeSpan.FromDays(7)); // Hangfire服务器配置 builder.Services.AddHangfireServer(options => { options.HeartbeatInterval = TimeSpan.FromSeconds(10); }); 使用Hangfire中间件: // 添加Hangfire Dashboard app.UseHangfireDashboard(); app.UseAuthorization(); app.MapControllers(); // 配置Hangfire Dashboard路径和权限控制 app.MapHangfireDashboard("/hangfire", new DashboardOptions { AppPath = null, DashboardTitle = "Hangfire Dashboard Test", Authorization = new [] { new HangfireCustomBasicAuthenticationFilter { User = app.Configuration.GetSection("HangfireCredentials:UserName").Value, Pass = app.Configuration.GetSection("HangfireCredentials:Password").Value } } }); 对应的配置如下: 1 appsettings.json "HangfireCredentials": { "UserName": "admin", "Password": "admin@123" } 编写Job Hangfire免费版本支持以下类型的定时任务: 周期性定时任务:Recurring Job 执行单次任务:Fire and Forget 连续顺序执行任务:Continouus Job 定时单次任务:Schedule Job Fire and Forget 这种类型的任务一般是在应用程序启动的时候执行一次结束后不再重复执行,最简单的配置方法是这样的: using Hangfire; BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire with Fire and Forget job!")); Continuous Job 这种类型的任务一般是进行顺序型的任务执行调度,比如先完成任务A,结束后执行任务B: var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire with Fire and Forget job!")); // Continuous Job, 通过指定上一个任务的Id来跟在上一个任务后执行 BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Hello world from Hangfire using continuous job!")); Scehdule Job 这种类型的任务是用于在未来某个特定的时间点被激活运行的任务,也被叫做Delayed Job: var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire with Fire and Forget job!")); // Continuous Job, 通过指定上一个任务的Id来跟在上一个任务后执行 BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Hello world from Hangfire using continuous job!")); Recurring Job 这种类型的任务应该是我们最常使用的类型,使用Cron表达式来设定一个执行周期时间,每到设定时间就被激活执行一次。对于这种相对常见的场景,我们可以演示一下使用单独的类来封装任务逻辑: IJob.cs namespace HelloHangfire; public interface IJob { public Task<bool> RunJob(); } Job.cs using Serilog; namespace HelloHangfire; public class Job : IJob { public async Task<bool> RunJob() { Log.Information($"start time: {DateTime.Now}"); // 模拟任务执行 await Task.Delay(1000); Log.Information("Hello world from Hangfire in Recurring mode!"); Log.Information($"stop time: {DateTime.Now}"); return true; } } 在Program.cs中使用Cron来注册任务: builder.Services.AddTransient<IJob, Job>(); // ... var app = builder.Build(); // ... var JobService = app.Services.GetRequiredService<IJob>(); // Recurring job RecurringJob.AddOrUpdate("Run every minute", () => JobService.RunJob(), "* * * * *"); Run 控制台输出: info: Hangfire.BackgroundJobServer[0] Starting Hangfire Server using job storage: 'Hangfire.MemoryStorage.MemoryStorage' info: Hangfire.BackgroundJobServer[0] Using the following options for Hangfire Server: Worker count: 20 Listening queues: 'default' Shutdown timeout: 00:00:15 Schedule polling interval: 00:00:15 info: Hangfire.Server.BackgroundServerProcess[0] Server b8d0de54-caee-4c5e-86f5-e79a47fad51f successfully announced in 11.1236 ms info: Hangfire.Server.BackgroundServerProcess[0] Server b8d0de54-caee-4c5e-86f5-e79a47fad51f is starting the registered dispatchers: ServerWatchdog, ServerJobCancellationWatcher, ExpirationManager, CountersAggregator, Worker, DelayedJobScheduler, RecurringJobScheduler... info: Hangfire.Server.BackgroundServerProcess[0] Server b8d0de54-caee-4c5e-86f5-e79a47fad51f all the dispatchers started Hello world from Hangfire with Fire and Forget job! Hello world from Hangfire using continuous job! info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:7295 info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5121 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: /Users/yu.li1/Projects/asinta/Net6Demo/HelloHangfire/HelloHangfire/ (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-web-api – 在ASP.NET Web API控制器的nunit测试中
- Jquery+ajax请求data显示在GridView上(asp.net)
- asp.net-mvc-3 – “区域”文件夹中的样式,脚本和图像
- ASP.Net:为什么我的按钮的点击/命令事件没有在转发器中绑定
- asp.net-mvc – 为什么MVC4捆绑捆绑Knockout.js?
- asp.net-mvc – 为什么ASP.NET MVC 4与IList for editor不能
- NHibernate中对同一个对象的Lazyload要设置一致
- asp.net-core – ClaimTypes的ASP.NET要求
- remoting和webservice有什么区别
- 实体框架 – 等同于.HasOptional在实体框架核心1(EF7)
推荐文章
站长推荐
- asp.net-mvc-3 – 为什么两个类,视图模型和域模型
- 遭遇Asp.Net长文件名下载的问题和解决办法
- asp.net-core – 我为什么要选择带有.Net核心的A
- asp.net 大文件上传 之 改版了的SlickUpload.Htt
- ASP.NET AJAX中的$create函数是什么?
- asp.net-mvc-3 – 剃刀引擎 – 如何根据不同的条
- ASP.NET Web API返回可查询的DTO?
- .net – TagBuilder从MVC 3 beta版转到RC
- asp.net-mvc – 如何正确识别vs2008版本级别?
- asp.net-mvc – 使ASP.NET绑定指定media =屏幕的
热点阅读