定時任務組件,除了 Hangfire 外,還有一個 Quarz.NET,不過 Hangfire .NET Core 支持的會更好些。html
ASP.NET Core 使用 Hangfire 很簡單,首先,Nuget 安裝程序包:數據庫
> install-package Hangfire -pre
而後ConfigureServices
添加配置代碼:app
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(x => x.UseSqlServerStorage("<name or connection string>")); }
上面配置的是 Hangfire 任務配置數據庫信息,默認只支持 SQLServer,若是不想使用數據庫的話,能夠 Nuget 安裝程序包:異步
> install-package Hangfire.MemoryStorage -pre
修改ConfigureServices
配置代碼:async
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(x => x..UseStorage(new MemoryStorage())); }
Hangfire 擴展(好比 MySql):https://www.hangfire.io/extensions.htmlide
而後Configure
添加配置代碼:ui
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseHangfireServer(); app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!"), Cron.Minutely()); }
上面配置代碼一分鐘執行一次,Hangfire 支持 UI 界面展現,地址:http://localhost:8089/hangfirespa
Hangfire 默認也支持執行異步方法,RecurringJob
方法簽名:code
public static void AddOrUpdate<T>(Expression<Func<T, Task>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default"); public static void AddOrUpdate(Expression<Func<Task>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default"); public static void AddOrUpdate<T>(Expression<Func<T, Task>> methodCall, Func<string> cronExpression, TimeZoneInfo timeZone = null, string queue = "default"); public static void AddOrUpdate(Expression<Func<Task>> methodCall, Func<string> cronExpression, TimeZoneInfo timeZone = null, string queue = "default");
異步和同步使用沒有任何區別,示例代碼:orm
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseHangfireServer(); app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() => TestAsync(), Cron.Minutely()); } public static async Task TestAsync() { // to do... }