前提
安装VS2022,自带.NET8
安装SqlServer2008R2
创建项目
安装包
<PackageReference Include="Hangfire" Version="1.8.6" /> <PackageReference Include="Hangfire.Core" Version="1.8.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
使用
-
appsettings.json
注意:TrustServerCertificate=True ; 不加有时候会报错
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "MyConn": "Server=.;Database=HangfireTest; User Id = sa; Password = sa;Integrated Security=SSPI;TrustServerCertificate=True" }, "AllowedHosts": "*" }
Program.cs
using Hangfire; using Hangfire.AspNetCore; using Hangfire.SqlServer; using System.Diagnostics; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); //读取 var conn = builder.Configuration.GetConnectionString("MyConn"); //hangfire builder.Services.AddHangfire(x => x .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(conn)); builder.Services.AddHangfireServer(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); //hangFire 面板 app.UseHangfireDashboard(); //Add job //第一种方式 var client = new BackgroundJobClient(); //立即执行 client.Enqueue(() => Console.WriteLine("hello hangfire")); //第二种方式 //立即执行 BackgroundJob.Enqueue(() => Console.WriteLine("Hello! now")); //延时任务 BackgroundJob.Schedule(() => Console.WriteLine("Schedule"), TimeSpan.FromDays(1)); //周期性 RecurringJob.AddOrUpdate(() => Console.WriteLine("Daliy Job"), Cron.Daily); //继续任务 //可以 通过将多个后台任务结合起来定义复杂的工作流 var id = BackgroundJob.Enqueue(() => Console.WriteLine("Hello first")); var seid = BackgroundJob.ContinueJobWith(id, () => Console.WriteLine(" go second!")); //操作周期任务 //删除 RecurringJob.RemoveIfExists(seid); //触发 //RecurringJob.Trigger(id); RecurringJob.TriggerJob(id); app.MapRazorPages(); app.Run();