最近公司的項目要求每小時計算數據並生成報告,使用的Hangfire來實現。git
以前對Hangfire並不瞭解,因此學習並記錄下來,但願對你們也有幫助。github
環境:數據庫
.NET Framework 4.7.2apache
Hangfire.Core 1.7.12app
Hangfire.AspNet 0.2.0框架
Hangfire.MySqlStorage 2.0.3ide
這篇文章主要根據官網的內網作一個基礎入門,實現最基礎的功能。學習
搭建基礎框架ui
首先,我建立了一個Web API項目,而後添加Startup類(由於我要使用Hangfire的Dashboard,因此使用Startup類進行配置)。spa
由於我使用的是MySQL數據庫(使用SQL Server能夠去看官網的例子),使用NuGet添加:
Install-Package Hangfire.MySqlStorage
能夠去GitHub查看這個包的說明:Hangfire MySql Storage
將官網的實例代碼複製到Startup類中,並修改了數據存儲的配置以下:
public class Startup { private IEnumerable<IDisposable> GetHangfireServers() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseStorage(new MySqlStorage("server=127.0.0.1;user id=root;password=111111;Database=hangfiretest;pooling=true;charset=utf8;Allow User Variables=True;", new MySqlStorageOptions { //CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), //SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), //QueuePollInterval = TimeSpan.Zero, //UseRecommendedIsolationLevel = true, //DisableGlobalLocks = true })); yield return new BackgroundJobServer(); } public void Configuration(IAppBuilder app) { app.UseHangfireAspNet(GetHangfireServers); app.UseHangfireDashboard(); // Let's also create a sample background job BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!")); // ...other configuration logic } }
說明:
There must be Allow User Variables
set to true
in the connection string. For example:
server=127.0.0.1;uid=root;pwd=root;database={0};Allow User Variables=True
這時候就能夠運行了 ,成功後能夠看獲得咱們建的空數據庫裏面已經有自動生成的表了,而且在輸出窗口中能夠看到任務執行輸出的:
Hello world from Hangfire!
在啓動的頁面地址後面加上 /hangfire,就能夠看到Dashboard頁面。
添加日誌功能
在遇到任務失敗的時候日誌能幫助咱們更好的查找問題。
Hangfire支持一下日誌框架(而且能夠自動識別項目中的引用,爲咱們記錄日誌):
若是項目中引用了多個日誌框架,日誌可能會失敗,你可使用下面的代碼來配置想使用的日誌框架
GlobalConfiguration.Configuration
.UseSerilogLogProvider()
.UseNLogLogProvider()
.UseLog4NetLogProvider()
.UseEntLibLogProvider()
.UseLoupeLogProvider()
.UseElmahLogProvider();
我用了NLog,這裏爲了讓其餘同事更清楚我配置了日誌功能,因此儘快Hangfire能夠自動識別,我仍是把這一句加上了。
而後我無情的發現日誌沒有生成,忘記了NLog的配置文件,添加上就行了。
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="true" internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log"> <!--throwExceptions 打印出Nlog的內部錯誤--> <!-- optional, add some variables https://github.com/nlog/NLog/wiki/Configuration-file#variables --> <variable name="myvar" value="myvalue"/> <!-- See https://github.com/nlog/nlog/wiki/Configuration-file for information on customizing logging rules and outputs. --> <targets> <!-- add your targets here See https://github.com/nlog/NLog/wiki/Targets for possible targets. See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers. --> <!-- Write events to a file with the date in the filename. <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> --> <!--文件--> <target name="fileLog" xsi:type="File" fileName="${basedir}/logs/${date:format=yyyyMM}/${shortdate}.log" layout="${longdate} ${logger} ${level:uppercase=true} ${message} ${exception:format=ToString}" /> </targets> <rules> <!-- add your logging rules here --> <!-- Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f" <logger name="*" minlevel="Debug" writeTo="f" /> --> <logger name="*" minlevel="Info" writeTo="fileLog" /> </rules> </nlog>
日誌成功生成