- 安装NuGet包
dotnet add package Hangfire.Core
dotnet add package Hangfire.SqlServer
dotnet add package Hangfire.AspNetCore
- 配置Hangfire
- 打开Startup.cs,在ConfigureServices方法中注册服务
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(App.Configuration["ConnectionStrings:HangfireConnection"], new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
services.AddHangfireServer();
}
- 在Configure方法中配置仪表盘
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] { new DashboardAuthorizationFilter() },
DashboardTitle = "Zheng He"
});
- 运行项目导航到/hangfire
- 创建单次执行任务
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
- 该方法不会立即调用目标方法,而是运行以下步骤
- 序列化方法信息及其所有参数
- 根据序列化信息创建新的后台作业
- 将后台作业保存到持久性存储
- 将后台作业排队到其队列
- 执行这些步骤后,该方法将立即返回给调用方。另一个Hangfire组件,称Hangfire Server,检查持久存储中排队的后台作业,并以可靠的方式执行它们
- 排队作业由专用的工作线程池处理。每个工作线程调用以下进程
- 获取下一个作业并将其隐藏起来
- 执行作业及其所有扩展筛选器
- 从队列中删除作业
- 因此只有在处理成功后才会删除作业。即使某个进程在执行期间被终止,Hangfire 也会执行补偿逻辑,以保证每个作业的处理
- 创建延迟执行任务
BackgroundJob.Schedule(() => Console.WriteLine("Hello, world"),TimeSpanFromDays(1));
- 创建重复执行任务
RecurringJob.AddOrUpdate("easyjob", () => Console.Write("Easy!"), CronDaily);
- 创建延续执行任务
var jobId = BackgroundJob.Enqueue(() => Console.WriteLin("Fire-and-forget!"));
//当上一个任务执行完成后,执行延续任务
BackgroundJob.ContinueJobWith(jobId,() => Console.WriteLine("Continuation!");
- 创建批量执行任务
var batchId = Batch.StartNew(x =>
{
x.Enqueue(() => Console.WriteLine("Job 1"));
x.Enqueue(() => Console.WriteLine("Job 2"));
});
- 创建批量延续执行任务
Batch.ContinueBatchWith(batchId, x =>
{
x.Enqueue(() => Console.WriteLine("Last Job"));
});