经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MySQL » 查看文章
.net core 基于Hangfire+Mysql持久化实现定时任务配置方法
来源:jb51  时间:2021/7/19 15:33:10  对本文有异议

1.negut引入hangfire相关包

Hangfire.AspNetCore,Hangfire.Core,Hangfire.Dashboard.BasicAuthorization,Hangfire.MySqlStorage

2.Appsetting 配置hangfire资源

  1. "HangFire": {
  2. "Connection": "Server=127.0.0.1;uid=root;pwd=wakamysql666;database=Hangfire_DB;AllowLoadLocalInfile=true;Allow User Variables=True;",
  3. "pathMatch": "/hangfire",
  4. "Login": "login",
  5. "PasswordClear": "pwd"
  6. },

3.自定义扩展类

  1. /// <summary>
  2. /// 任务调度
  3. /// </summary>
  4. public static class HangfireSetup
  5. {
  6. public static void AddHangfireSetup(this IServiceCollection services)
  7. {
  8. if (services == null) throw new ArgumentNullException(nameof(services));
  9. if (services == null) throw new ArgumentNullException(nameof(services));
  10. services.AddHangfire(configuration => configuration
  11. .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)//此方法 只初次创建数据库使用即可
  12. .UseSimpleAssemblyNameTypeSerializer()
  13. .UseRecommendedSerializerSettings()
  14. .UseStorage(new MySqlStorage(Appsettings.app("HangFire", "Connection"), new MySqlStorageOptions
  15. {
  16. TransactionIsolationLevel =
  17. (IsolationLevel?) System.Data.IsolationLevel.ReadCommitted, //事务隔离级别。默认是读取已提交
  18. QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。
  19. JobExpirationCheckInterval = TimeSpan.FromHours(1),
  20. CountersAggregateInterval = TimeSpan.FromMinutes(5),
  21. PrepareSchemaIfNecessary = false, // 如果设置为true,则创建数据库表。默认是true
  22. DashboardJobListLimit = 50000,
  23. TransactionTimeout = TimeSpan.FromMinutes(1),
  24. TablesPrefix = "Hangfire"
  25. })));
  26. services.AddHangfireServer();
  27. }
  28. }

4.在startupConfigureServices注入扩展

  1. services.AddHangfireSetup();//任务调度

5.配置MIddleware

  1. //任务调度中间件
  2. public static class HangfireMiddleware
  3. {
  4. public static void UseHangfireMiddleware(this IApplicationBuilder app)
  5. {
  6. if (app == null) throw new ArgumentNullException(nameof(app));
  7. app.UseHangfireServer(); //配置服务//ConfigureOptions()
  8. app.UseHangfireDashboard(Appsettings.app("HangFire", "pathMatch"), HfAuthor()); //配置面板
  9. //BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
  10. HangfireService(); //配置各个任务
  11. }
  12.  
  13. /// <summary>
  14. /// 配置账号模板信息
  15. /// </summary>
  16. /// <returns></returns>
  17. public static DashboardOptions HfAuthor()
  18. {
  19. var filter = new BasicAuthAuthorizationFilter(
  20. new BasicAuthAuthorizationFilterOptions
  21. {
  22. SslRedirect = false,
  23. RequireSsl = false,
  24. LoginCaseSensitive = false,
  25. Users = new[]
  26. {
  27. new BasicAuthAuthorizationUser
  28. {
  29. Login = Appsettings.app("HangFire", "Login"), //可视化的登陆账号
  30. PasswordClear = Appsettings.app("HangFire", "PasswordClear") //可视化的密码
  31. }
  32. }
  33. });
  34. return new DashboardOptions
  35. {
  36. Authorization = new[] {filter}
  37. };
  38. }
  39.  
  40. /// <summary>
  41. /// 配置启动
  42. /// </summary>
  43. /// <returns></returns>
  44. public static BackgroundJobServerOptions ConfigureOptions()
  45. {
  46. return new()
  47. {
  48. Queues = new[] {"Job", nameof(HangfireConfigureQueue.picturetooss)}, //队列名称,只能为小写
  49. WorkerCount = Environment.ProcessorCount * 5, //并发任务
  50. ServerName = "HangfireServer" //代表服务名称
  51. };
  52. }
  53.  
  54. #region 配置服务
  55.  
  56. public static void HangfireService()
  57. {
  58. // "0 0 1 * * ? " 每天凌晨一点执行阿里云OSS
  59. RecurringJob.AddOrUpdate<IOrderItemInfoService>(_ => _.JobOSS(), "0 0 1 * * ? ", TimeZoneInfo.Local,
  60. nameof(HangfireConfigureQueue.picturetooss));
  61.  
  62. // "0 0 1 * * ? " 每天早上七点执行定时任务更新汇率
  63. RecurringJob.AddOrUpdate<ICurrencyInfosService>(_ => _.UpdateRateByJob(), "0 0 7 * * ? ",
  64. TimeZoneInfo.Local, nameof(HangfireConfigureQueue.picturetooss));
  65. }
  66.  
  67. #endregion
  68. }

6.startupConfigure配置使用中间件

  1. app.UseHangfireMiddleware();//Job

效果图:

结语:到此hangfire实现定时任务的配置已经全部完成。

到此这篇关于.net core 基于Hangfire+Mysql持久化实现定时任务的文章就介绍到这了,更多相关.net core Hangfire定时任务内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号