以前使用Quartz.Net,後來發現hangfire對Core的繼承更加的好,並且自帶管理後臺,這就比前者好用太多了。html
安裝git
PM> Install-Package Hangfire
Startup.cs,在ConfigureServices
方法中添加註冊:github
services.AddHangfire(x => x.UseSqlServerStorage("connection string"));
SqlServer是使用這種方式,其餘方式見官方的文檔及相應插件。shell
註冊完成後,還須要在Configure方法中,添加以下高亮部分的代碼:數據庫
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } //添加Hangfire app.UseHangfireServer(); app.UseHangfireDashboard();
配置完畢後運行咱們的項目,這時Hangfire會自動在數據庫中建立結構,數據庫中會新建以下表:
如今在網站根目錄+/Hangfire便可查看管理後臺界面以下:express
Hangfire的使用很是簡單,基本上使用如下幾個靜態方法:bash
//執行後臺腳本,僅執行一次 BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!")); //延遲執行後臺腳本呢,僅執行一次 BackgroundJob.Schedule( () => Console.WriteLine("Delayed!"), TimeSpan.FromDays(7)); //週期性任務 RecurringJob.AddOrUpdate( () => Console.WriteLine("Recurring!"), Cron.Daily); //等上一任務完成後執行 BackgroundJob.ContinueWith( jobId, //上一個任務的jobid () => Console.WriteLine("Continuation!"));
注意,週期性使用可使用Cron表達式。app
# ┌───────────── minute (0 - 59) # │ ┌───────────── hour (0 - 23) # │ │ ┌───────────── day of the month (1 - 31) # │ │ │ ┌───────────── month (1 - 12) # │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday; # │ │ │ │ │ 7 is also Sunday on some systems) # │ │ │ │ │ # │ │ │ │ │ # * * * * * command to execute
Entry | Description | Equivalent to |
---|---|---|
@yearly (or @annually) |
每一年1月3號2:01分運行 | 1 2 3 1 * |
@monthly |
每個月3號2:01分運行 | 1 2 3 * * |
@weekly |
每週日的2:01分運行 | 1 2 * * 0 |
@daily |
天天的2:01分運行 | 1 2 * * * |
@hourly |
每小時的1分運行 | 1 * * * * |
@reboot |
Run at startup | N/A |
在.Net Core中到處是DI,一不當心,你會發現你在使用Hangfire的時候會遇到各類問題,好比下列代碼:less
public class HomeController : Controller { private ILogger<HomeController> _logger; public HomeController(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<HomeController>(); } public IActionResult Index() { _logger.LogInformation("start index"); BackgroundJob.Enqueue(() => _logger.LogInformation("this a job!")); return View(); } }
項目啓動後,你能正常訪問,但在Hangfire後臺你會看到以下錯誤:ide
錯誤信息呢大概意思是不能使用接口或者抽象方法類,其實就是由於Hangfire沒有找到實例,那如何讓Hangfire支持DI呢?
咱們先建立一個MyActivator
類,使其繼承Hangfire.JobActivator
類,代碼以下:
public class MyActivator : Hangfire.JobActivator { private readonly IServiceProvider _serviceProvider; public MyActivator(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; public override object ActivateJob(Type jobType) { return _serviceProvider.GetService(jobType); } }
重寫了ActivateJob方法,使其返回的類型從咱們的IServiceProvider中獲取。
咱們試着寫兩個後臺腳本,CheckService和TimerService,CheckService的Check方法在執行計劃時,會再次調用Hangfire來定時啓動TimerService:
CheckService:
public interface ICheckService { void Check(); } public class CheckService : ICheckService { private readonly ILogger<CheckService> _logger; private ITimerService _timeservice; public CheckService(ILoggerFactory loggerFactory, ITimerService timerService) { _logger = loggerFactory.CreateLogger<CheckService>(); _timeservice = timerService; } public void Check() { _logger.LogInformation($"check service start checking, now is {DateTime.Now}"); BackgroundJob.Schedule(() => _timeservice.Timer(), TimeSpan.FromMilliseconds(30)); _logger.LogInformation($"check is end, now is {DateTime.Now}"); } }
TimerService:
public interface ITimerService { void Timer(); } public class TimerService : ITimerService { private readonly ILogger<TimerService> _logger; public TimerService(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<TimerService>(); } public void Timer() { _logger.LogInformation($"timer service is starting, now is {DateTime.Now}"); _logger.LogWarning("timering"); _logger.LogInformation($"timer is end, now is {DateTime.Now}"); } }
目前還沒法使用,咱們必須在Startup
中註冊這2個service:
services.AddScoped<ITimerService, TimerService>();
services.AddScoped<ICheckService, CheckService>();
咱們在HomeController
修改如下:
public IActionResult Index() { _logger.LogInformation("start index"); BackgroundJob.Enqueue<ICheckService>(c => c.Check()); return View(); }
好,一切就緒,只差覆蓋原始的Activator了,咱們能夠在Startup.cs
中的Configure
方法中使用以下代碼:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { GlobalConfiguration.Configuration.UseActivator<MyActivator>(new MyActivator(serviceProvider)); …… …… }
默認狀況下Configure方法時沒有IServiceProvider參數的,請手動添加
再次啓動,咱們的Job就會成功執行,截圖以下:
401 Unauthorized
未受權錯誤,緣由是 Hangfire 默認增長了受權配置。解決方式:
增長CustomAuthorizeFilter
:
public class CustomAuthorizeFilter : IDashboardAuthorizationFilter { public bool Authorize([NotNull] DashboardContext context) { //var httpcontext = context.GetHttpContext(); //return httpcontext.User.Identity.IsAuthenticated; return true; } }
Configure
增長配置:
app.UseHangfireDashboard("/hangfire", new DashboardOptions() { Authorization = new[] { new CustomAuthorizeFilter() } });