ASP.NET Core 使用 Hangfire 定時任務

定時任務組件,除了 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

435188-20170425202305678-916877046.png

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...
}
相關文章
相關標籤/搜索