.NET Core下開源任務調度框架Hangfire


今天無意中發現了一個很好用的任務調度框架。Hangfire作為一款高人氣且容易上手的分布式后台執行服務,支持多種數據庫。在 .net core的環境中,由Core自帶的DI管理着生命周期。

相較於quartz.net相比,最大的優點是有個自帶的監控界面,比較方便。最新版已經支持秒級任務。

官網地址:https://www.hangfire.io/

基於隊列的任務處理(Fire-and-forget jobs)

基於隊列的任務處理是Hangfire中最常用的,客戶端使用BackgroundJob類的靜態方法Enqueue來調用,傳入指定的方法(或是匿名函數),Job Queue等參數.(類似MQ)

var jobId = BackgroundJob.Enqueue(
    () => Console.WriteLine("Fire-and-forget!"));

延遲任務執行(Delayed jobs)

延遲(計划)任務跟隊列任務相似,客戶端調用時需要指定在一定時間間隔后調用:

var jobId = BackgroundJob.Schedule(
    () => Console.WriteLine("Delayed!"),
    TimeSpan.FromDays(7));

定時任務執行(Recurring jobs)

定時(循環)任務代表可以重復性執行多次,支持CRON表達式:

RecurringJob.AddOrUpdate(
    () => Console.WriteLine("Recurring!"),
    Cron.Daily);

延續性任務執行(Continuations)

延續性任務類似於.NET中的Task,可以在第一個任務執行完之后緊接着再次執行另外的任務:

BackgroundJob.ContinueWith(
    jobId,
    () => Console.WriteLine("Continuation!"));

基於SQL的實現

修改startup.cs類中的ConfigureServices()方法中注入

services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
{
    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
    QueuePollInterval = TimeSpan.Zero,
    UseRecommendedIsolationLevel = true,
    UsePageLocksOnDequeue = true,
    DisableGlobalLocks = true
}));
services.AddHangfireServer();

封裝一下

 public static void AddHangfireExt(this IServiceCollection services, IConfiguration Configuration)
{
    services.AddHangfire(configuration => configuration
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
            {
                CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                QueuePollInterval = TimeSpan.Zero,
                UseRecommendedIsolationLevel = true,
                UsePageLocksOnDequeue = true,
                DisableGlobalLocks = true
            }));

    services.AddHangfireServer();
}

修改ConfigureServices方法

services.AddHangfireExt(Configuration);

修改Configure()方法

  //啟用監控面板
  app.UseHangfireDashboard();
  //增加隊列任務
  backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
  RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!"),Cron.Minutely);

我這里只做了SQL數據庫,建議改成redis,提高性能。

Hangfire UI

瀏覽器打開http://{host:poort}/hangfire/地址,可以看到如下界面:

  • 儀表盤

  • 可以看到周期性作業列表

還可以加上授權等,先介紹到這里,詳細文檔可以參考官方文檔。


免責聲明!

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



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