Hangfire帶管理后台的一個任務調度,免費開源、擴展包PRO收費
Quick Start
1.新建空的.Net core web項目,添加Nuget包
Install-Package Hangfire
2.修改Startup.cs
public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddHangfire(x => x.UseSqlServerStorage("Data Source=.;Initial Catalog=HangFire;User ID=sa;Password=sasa")); services.AddHangfireServer(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHangfireServer(); app.UseHangfireDashboard(); app.Run(context => { return context.Response.WriteAsync("Hello from ASP.NET Core!"); }); } }
至此即可運行查看效果https://localhost:44319/hangfire;當然現在還沒有任務被調度。
任務調度:
[Route("[controller]/[action]")] [ApiController] public class DemoController : Controller { #region BackgroundJob [HttpGet] public string One() { //基於任務隊列 //任務執行一次 var jobId = BackgroundJob.Enqueue(() => Console.WriteLine($"OneTime:{DateTime.Now}")); return "OK," + jobId; } [HttpGet] public string DelayDemo() { //延時任務 //任務延時兩分鍾執行 Hangfire.BackgroundJob.Schedule(() => Console.WriteLine($"Delay two minute:{DateTime.Now}"), TimeSpan.FromMinutes(2)); return "OK"; } [HttpGet] public string ContinueJobDemo() { //連續執行任務 var jobId = BackgroundJob.Schedule(() => Console.WriteLine($"Delay two minute:{DateTime.Now}"), TimeSpan.FromMinutes(2)); BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!")); return "OK"; } #endregion [HttpGet] public string CronDemo() { //Cron方式 //任務每分鍾執行一次 RecurringJob.AddOrUpdate(() => Console.WriteLine($"Every minute:{DateTime.Now}"), Cron.Minutely()); return "OK"; } public string BatchJobDemo() { //PRO 版本 支持 //var batchId =Batch.StartNew(x => //{ // x.Enqueue(() => Console.WriteLine("Job 1")); // x.Enqueue(() => Console.WriteLine("Job 2")); //}); //Batch.ContinueWith(batchId, x => //{ // x.Enqueue(() => Console.WriteLine("Last Job")); //}); return "OK"; } }
資源:
GitHub:https://github.com/HangfireIO/Hangfire
http://hangfire.io/
http://docs.hangfire.io/en/latest/