ASP.NET Core 使用 Hangfire 定時任務


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM