文章出處

定時任務組件,除了 Hangfire 外,還有一個 Quarz.NET,不過 Hangfire .NET Core 支持的會更好些。

ASP.NET Core 使用 Hangfire 很簡單,首先,Nuget 安裝程序包:

> install-package Hangfire -pre

然后ConfigureServices添加配置代碼:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHangfire(x => x.UseSqlServerStorage("<name or connection string>"));
}

上面配置的是 Hangfire 任務配置數據庫信息,默認只支持 SQLServer,如果不想使用數據庫的話,可以 Nuget 安裝程序包:

> install-package Hangfire.MemoryStorage -pre

修改ConfigureServices配置代碼:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHangfire(x => x..UseStorage(new MemoryStorage()));
}

Hangfire 擴展(比如 MySql):https://www.hangfire.io/extensions.html

然后Configure添加配置代碼:

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/hangfire

Hangfire 默認也支持執行異步方法,RecurringJob方法簽名:

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");

異步和同步使用沒有任何區別,示例代碼:

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...
}

參考資料:


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()