Hangfire容許您以很是簡單但可靠的方式執行後臺定時任務的工做。內置對任務的可視化操做。很是方便。git
但使人遺憾的是廣泛都是業務代碼和hagnfire服務自己聚合在一個程序中運行,極大的限制了hangfire的擴展和跨語言調用。github
因此萌生了開發一個支持restful api調用的sdk庫web
原本打算簡單的創建webapi,內部再調用hangfire,可是一想實在不優雅,組件就應該儘可能聚合在一個庫的中,偶然找到了一個已經開發了支持restfull api的hangfire組件,github地址=>Hangfire.Job數據庫
看了下源碼,調用了hangfire公開的接口獲取請求路由信息,而後去hangfire去執行。只提供了單次執行和循環執行,其餘場景能夠參考代碼擴展。json
可是調用方要經過http請求,不是很方便,因此擴展了一個Chaunce.Hangfire.Client 的C# sdk來調用hangfire。此庫也已上傳nugetapi
部署hangfire服務restful
拉取Chaunce.Hangfire.Server(屬於.netcore程序,支持跨平臺部署)項目app
而後修改appsettings.json文件asp.net
"ConnectionStrings": {
"HangfireConnection": "server=.;database={你想讓hangfire生成的數據庫名稱};uid=sa;pwd=111111"
},
以後在數據庫創建與ppsettings.json中數據庫名稱一致的數據庫。async
使用hangfire客戶端
創建asp.netcore 程序,並修改appsettings.json文件以下:
"HangfireClientOptions": {
"RecurringJobUrl": "hangfire/httpjob?op=recurringjob",
"BackgroundJobUrl": "",
"BaseUrl": "http://localhost:5000",
"UserName": "admin",
"PassWord":"test"
}
修改Startup文件將Chaunce.Hangfire.Client註冊到asp.netcore組件中,
public void ConfigureServices(IServiceCollection services) { var option = Configuration.GetSection(nameof(HangfireClientOptions)).Get<HangfireClientOptions>(); services.AddHangfireClient(option); }
這裏以Controller中使用爲例:將IHangfireClient 注入構造函數進行使用
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHangfireClient _hangfireClient; public ValuesController(IHangfireClient hangfireClient) { _hangfireClient = hangfireClient; } // GET api/values [HttpGet] public async Task<ActionResult<IEnumerable<string>>> Get() { var result = await _hangfireClient.SendTimerJobAsync(new HttpJobItem { Corn = Cron.MinuteInterval(10), Url = "https://www.cnblogs.com/xiaoliangge/", JobName = "I'm external Job by restful Api", }, TaskType.Recurringjob); return new string[] { "Do i succeeded?", $"{result}" }; } }