hangfire 是一個分布式后台執行服務。用它可以代替ThreadPool.QueunItemWork等原生方法。當然4.5后的 task也是相當好用且功能強大。不過如果想分布式處理並且可監控的話,hangfire絕對滿足需求。
我使用hangfire更看重監控層面。
hangfire的執行步驟:
1.客戶端創建一個job任務
2.持久化job數據
3.服務端定時fetch數據源
4.如果規則匹配則通過子線程執行job
Client端:
配置:
public void Configuration(IAppBuilder app) { app.UseHangfire(config => { config.UseSqlServerStorage("<connection string or its name>"); //config.UseServer(); // 加上這句客戶端和服務端就真在一起了 }); }
Enqueue 方法: 放入隊列執行。執行后銷毀
BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));
Schedule方法: 延遲執行。第二個參數設置延遲時間。
BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1));
AddOrUpdate方法:重復執行。第二個參數設置cronexpression表達式。
參考quartz文檔:http://jingyan.baidu.com/article/a3761b2b8e843c1576f9aaac.html
RecurringJob.AddOrUpdate(() => Console.Write("Recurring"), Cron.Daily);
Server端:
namespace WindowsService1 { public partial class Service1 : ServiceBase { private readonly BackgroundJobServer _server; public Service1() { InitializeComponent(); JobStorage.Current = new SqlServerStorage("connection_string"); _server = new BackgroundJobServer(); } protected override void OnStart(string[] args) { _server.Start(); } protected override void OnStop() { _server.Dispose(); } } }