Hangfire定时任务
Hangfire定时任务
HangFire
- HangFire官方网址:https://www.hangfire.io/
- HangFire 中文文档:https://www.bookstack.cn/read/Hangfire-zh-official/README.md
下载NuGut包
- Hangfire是基础的包
- Hangfire.HttpJob 是仪表盘任务
连接数据库
- CREATE DATABASE HangFireText 数据库创建数据表
- "ConnectionStrings": { "HangFire": "server=LAPTOP-TBKRP9BV;uid=sa;pwd=123456;database=HangFireText;TrustServerCertificate=True" }
配置连接数据库
生成的表
配置HangFire
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());
- builder.Services.AddHangfireServer();
- 创建仪表盘登录验证
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并复制路径
- 更改后缀
- 仪表盘页面
仪表盘核心功能,可以添加作业,周期性运行作业
通过cron表达式来给每一个作业添加周期
cron表达式网址 cron.ciding.cc
定时执行日志功能
- 在项目中引用nlog日志
builder.Host.UseNLog();
- 控制器中创建方法
- 仪表盘新增日志任务
- 运行日志方法
- 查看运行效果