1. 组件选择与总体架构
- 组件:Hangfire(成熟、可视化 Dashboard、持久化、失败重试、并发控制、队列机制完善)
- 存储:
- 开发环境:使用本地 SQL Server(不使用内存存储)
- 生产环境:SQL Server(推荐)
- 使用与业务相同的 DefaultConnection 连接(不单独新建数据库),Hangfire 启动时自动建表
- 承载:API 进程内 Running Server(AddHangfireServer)
- 安全:Dashboard 仅对 SuperAdmin 开放;管理接口鉴权拦截
2. 包依赖与安装位置
- 安装到 Server/API 项目(WebHost 承载 Dashboard 与 Server):
powershell
# 必选
cd Server/API
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
# 可选(调试增强)
dotnet add package Hangfire.Console3. 目录与代码规划(最终版)
为理清分层职责:
- 公共与基础设施能力(Cron/Catch/常量等)统一放到 Common/Infrastructure/BackgroundJobs。
- 业务作业代码(Job 实现与注册器)统一放到 Services/BackgroundJobs。
- Dashboard 鉴权仍放 API 层。
目录结构:
Server/Common/Infrastructure/BackgroundJobs/
├─ CronHelper.cs # 常用 Cron 封装
├─ SafeJobRunner.cs # 统一异常与日志包装
└─ JobIds.cs # 任务ID常量
Server/Services/BackgroundJobs/
├─ Jobs/
│ ├─ System/
│ │ ├─ CleanupLogsJob.cs # 系统日志清理
│ │ └─ RefreshCachesJob.cs # 缓存刷新(示例)
│ ├─ Member/
│ │ └─ ClearExpiredVerificationsJob.cs # 清理过期验证码/令牌
│ └─ Content/
│ └─ DailyStatsAggregationJob.cs # 内容/课程统计汇总
└─ Scheduling/
└─ HangfireJobRegistrar.cs # 统一注册入口(应用启动时调用)
Server/API/Filters/
└─ HangfireDashboardAuthorizationFilter.cs # Dashboard 鉴权3.1 Common/Infrastructure/BackgroundJobs(通用工具)
csharp
// Server/Common/Infrastructure/BackgroundJobs/CronHelper.cs
using Hangfire;
namespace Common.Infrastructure.BackgroundJobs
{
public static class CronHelper
{
public static string EveryMinute => Cron.Minutely();
public static string Every5Minutes => "*/5 * * * *";
public static string Hourly => Cron.Hourly();
public static string DailyAt(int hour, int minute = 0) => Cron.Daily(hour, minute);
public static string Weekly(DayOfWeek dow, int hour, int minute = 0) => Cron.Weekly(dow, hour, minute);
}
}csharp
// Server/Common/Infrastructure/BackgroundJobs/SafeJobRunner.cs
using Microsoft.Extensions.Logging;
namespace Common.Infrastructure.BackgroundJobs
{
public static class SafeJobRunner
{
public static async Task RunAsync(Func<Task> action, ILogger logger, string jobName)
{
try { await action(); }
catch (Exception ex)
{
logger.LogError(ex, "Job {JobName} failed: {Message}", jobName, ex.Message);
throw; // 交由 Hangfire 记录与重试
}
}
}
}csharp
namespace Common.Infrastructure.BackgroundJobs
{
public static class JobIds
{
public const string DailyStatsAggregation = "stats:daily-aggregation";
public const string ClearExpiredVerifications = "auth:clear-expired-verifications";
public const string CleanupLogs = "system:cleanup-logs";
public const string RefreshCaches = "system:refresh-caches";
}
}3.2 Services/BackgroundJobs/Jobs(作业实现)
csharp
using Common.Infrastructure.BackgroundJobs;
using Microsoft.Extensions.Logging;
namespace Services.Shared.BackgroundJobs.Jobs.System
{
public class CleanupLogsJob(ILogger<CleanupLogsJob> logger)
{
public async Task ExecuteAsync()
=> await SafeJobRunner.RunAsync(async () =>
{
// TODO: 删除30天前日志(调用仓储/服务)
await Task.CompletedTask;
logger.LogInformation("CleanupLogsJob completed");
}, logger, nameof(CleanupLogsJob));
}
}csharp
using Common.Infrastructure.BackgroundJobs;
using Microsoft.Extensions.Logging;
namespace Services.Shared.BackgroundJobs.Jobs.Member
{
public class ClearExpiredVerificationsJob(ILogger<ClearExpiredVerificationsJob> logger)
{
public async Task ExecuteAsync()
=> await SafeJobRunner.RunAsync(async () =>
{
// TODO: 清理过期验证码/令牌
await Task.CompletedTask;
logger.LogInformation("ClearExpiredVerificationsJob completed");
}, logger, nameof(ClearExpiredVerificationsJob));
}
}csharp
using Common.Infrastructure.BackgroundJobs;
using Microsoft.Extensions.Logging;
namespace Services.Shared.BackgroundJobs.Jobs.Content
{
public class DailyStatsAggregationJob(ILogger<DailyStatsAggregationJob> logger)
{
public async Task ExecuteAsync()
=> await SafeJobRunner.RunAsync(async () =>
{
// TODO: 聚合统计写入统计表/缓存
await Task.CompletedTask;
logger.LogInformation("DailyStatsAggregationJob completed");
}, logger, nameof(DailyStatsAggregationJob));
}
}3.3 Services/BackgroundJobs/Scheduling(统一注册)
csharp
using Common.Infrastructure.BackgroundJobs;
using Hangfire;
using Services.Shared.BackgroundJobs.Jobs.Content;
using Services.Shared.BackgroundJobs.Jobs.Member;
using Services.Shared.BackgroundJobs.Jobs.System;
namespace Services.Shared.BackgroundJobs.Scheduling
{
public static class HangfireJobRegistrar
{
public static void RegisterRecurringJobs(IRecurringJobManager manager)
{
manager.AddOrUpdate<DailyStatsAggregationJob>(
JobIds.DailyStatsAggregation,
job => job.ExecuteAsync(),
CronHelper.DailyAt(0, 10));
manager.AddOrUpdate<ClearExpiredVerificationsJob>(
JobIds.ClearExpiredVerifications,
job => job.ExecuteAsync(),
CronHelper.Every5Minutes);
manager.AddOrUpdate<CleanupLogsJob>(
JobIds.CleanupLogs,
job => job.ExecuteAsync(),
CronHelper.DailyAt(2));
}
}
}3.4 API 层(注册、Dashboard 与权限)
- Program.cs(或 Startup.cs)注册(使用 DefaultConnection,不单独新库):
csharp
using Hangfire;
using Hangfire.SqlServer;
using Services.Shared.BackgroundJobs.Scheduling;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHangfire(cfg =>
{
cfg.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnection"), new SqlServerStorageOptions
{
QueuePollInterval = TimeSpan.FromSeconds(15),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
UseRecommendedIsolationLevel = true,
UsePageLocksOnDequeue = true,
DisableGlobalLocks = true
});
});
builder.Services.AddHangfireServer(options =>
{
options.WorkerCount = Environment.ProcessorCount;
options.Queues = new[] { "default" };
});
var app = builder.Build();
app.UseHangfireDashboard("/admin/hangfire", new DashboardOptions
{
Authorization = new[] { new HangfireDashboardAuthorizationFilter() }
});
using (var scope = app.Services.CreateScope())
{
var recurring = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
HangfireJobRegistrar.RegisterRecurringJobs(recurring);
}
app.Run();- Dashboard 授权过滤器:
csharp
using Hangfire.Dashboard;
namespace API.Filters
{
public class HangfireDashboardAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
return httpContext.User?.Identity?.IsAuthenticated == true
&& httpContext.User.IsInRole("SuperAdmin");
}
}
}4. 公共代码清单(回顾)
- Common/Infrastructure/BackgroundJobs
- CronHelper:常用 Cron 封装
- SafeJobRunner:统一异常捕获与日志记录
- JobIds:统一管理任务 ID
- (可选)JobLock/分布锁封装、Job 运行上下文等
5. 可集成的必要定时任务(建议)
- 认证类:清理过期验证码/找回密码 Token(每5分钟);清理过期 RefreshToken / 登录会话(每日)
- 系统类:清理过期日志/操作记录(每日 02:00);缓存刷新(每小时)
- 内容与会员:每日课程/内容/访问统计汇总(每日 00:10);会员活跃度统计、到期/待审提醒(每日)
- 站点:生成站点地图/搜索索引(每日/每周)
6. 目录与注册约定
- 类名以 Job 结尾,提供 ExecuteAsync()
- 注册统一由 HangfireJobRegistrar 进行,使用 JobIds 统一命名
- 并发保护可在 ExecuteAsync 上增加特性:
csharp
[Hangfire.DisableConcurrentExecution(timeoutInSeconds: 1800)]7. API 层改造要点
- Program/Startup:AddHangfire + AddHangfireServer + UseHangfireDashboard(DefaultConnection)
- 启动时 scope 注册周期任务
- Dashboard 授权过滤器仅放行 SuperAdmin
- 可选提供 /admin/jobs 管理接口(重新注册、手动触发)
8. 运维与安全建议
- Worker:默认按 CPU 核心数分配,可视流量与作业耗时调优
- 队列:将耗时/非关键任务放入 slow 队列,关键任务留在 default
- 重试:使用 Hangfire 默认重试机制,必要时在作业内做幂等
- 监控:启用 Dashboard;如需外部告警,可在 SafeJobRunner 捕获时发送邮件/IM 通知
- 数据清理:定期清理 Hangfire 历史数据(可用内置清理器或自定义 Job)
- 安全:Dashboard 路由前加额外网关限制或 IP 白名单;接口层严格鉴权
9. 最小上线步骤(Checklist)
- 在 Server/API 安装包(第2节)
- 新建 Common/Infrastructure/BackgroundJobs 与 Services/BackgroundJobs 目录及代码(第3节)
- Program.cs 接入 Hangfire(使用 DefaultConnection)并注册周期任务
- 放通 /admin/hangfire(仅 SuperAdmin),验证 Dashboard 与执行情况
- (可选)新增 /admin/jobs 管理接口
