Hangfire定时任务

Hangfire定时任务

HangFire

  1. HangFire官方网址:https://www.hangfire.io/

descript

  1. HangFire 中文文档:https://www.bookstack.cn/read/Hangfire-zh-official/README.md

下载NuGut包

descript

  1. Hangfire是基础的包
  2. Hangfire.HttpJob 是仪表盘任务

连接数据库

  1. CREATE DATABASE HangFireText 数据库创建数据表
  2. "ConnectionStrings": { "HangFire": "server=LAPTOP-TBKRP9BV;uid=sa;pwd=123456;database=HangFireText;TrustServerCertificate=True" }

配置连接数据库

descript

生成的表

配置HangFire

descript

var Config = builder.Configuration;

builder.Services.AddHangfire(config => config

.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)

.UseSimpleAssemblyNameTypeSerializer()

.UseRecommendedSerializerSettings()

.UseStorage(new SqlServerStorage(

Config["ConnectionStrings:HangFire"],

new SqlServerStorageOptions

{

CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), //命令批处理最大超时

SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),//滑动隐形超时

QueuePollInterval = TimeSpan.FromSeconds(15), //队列轮询间隔

UseRecommendedIsolationLevel = true, //使用推荐隔离级别

UsePageLocksOnDequeue = true, //使用页面锁定取消排队

DisableGlobalLocks = true, //禁用全局锁

})).UseHangfireHttpJob());

  1. builder.Services.AddHangfireServer();
  2. 创建仪表盘登录验证

app.UseHangfireDashboard("/Hangfire", new DashboardOptions

{

Authorization = new[] {new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions

{

RequireSsl =false,

SslRedirect =false,

LoginCaseSensitive = true,

Users = new[]

{

//授权登录

new BasicAuthAuthorizationUser

{

Login ="admin",

PasswordClear = "123456",

}

}

})}

});

app.UseRouting();

仪表盘使用

1.启动swagger并复制路径

descript

  1. 更改后缀

descript

  1. 仪表盘页面

descript

descript

仪表盘核心功能,可以添加作业,周期性运行作业

通过cron表达式来给每一个作业添加周期

cron表达式网址 cron.ciding.cc

定时执行日志功能

  1. 在项目中引用nlog日志

builder.Host.UseNLog();

  1. 控制器中创建方法

descript

  1. 仪表盘新增日志任务

descript

  1. 运行日志方法

descript

  1. 查看运行效果

descript

posted @ 2024-06-05 09:51  北落师门、  阅读(68)  评论(0编辑  收藏  举报