今天在園子裏看到一篇關於Hangfire這個後臺任務組件的文《執行後臺任務的利器——Hangfire》在根據Hangfire官方的文檔docs.hangfire.io/en/latest/完成了這個後臺執行完任務後推送消息給前端頁面的簡單功能。
1.使用NuGet安裝Hangfire和SignalR所須要的組件(基於.NET Framework 4.5)。
2.配置Hangfire,添加 OWIN Startup類以下
[assembly: OwinStartup(typeof(MyHangfireTest.Startup))] namespace MyHangfireTest { public class Startup { private readonly string HangFireDB = @"Server=localhost;Database=CollegeDB;Uid=123;Pwd=123;"; public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage(HangFireDB); app.UseHangfireDashboard(); app.UseHangfireServer(); } } }
編譯後打開瀏覽器輸入:http://<your-site>/hangfire會出現以下的頁面,說明配置成功了!
3.添加集線器類,和自定義的消息類
public class MessageHub : Hub { public Message Send() { Message m = Message.getMessage(); return m; } } public class Message { public string Time { get; set; } public string Msg { get; set; } public static Message GetMessage() { Random r = new Random(); Message m = new Message { Time = "任務執行時間" + DateTime.Now.ToString(), Msg = "生成的隨機數: " + r.Next(1, 100).ToString() }; return m; } }
4.在控制器中添加Action並添加相應的頁面用於顯示消息,引入signalR.js.創建與服務端的連接
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script> <script src="/signalr/hubs"></script> <script type="text/javascript"> $(function () { var chat = $.connection.messageHub function init() { chat.server.send().done(function (messages) { var dis = $("#discussion"); dis.append('<li><strong>' + messages.Time + '</strong>: ' + messages.Msg + '</li>'); }); } $.extend(chat.client, { updateInfo: function () { return init(); } }); $.connection.hub.start().pipe(init);//開啓客戶端SignalR,並首次運行init }); </script> </head> <body> <div class="container"> <ul id="discussion"></ul> </div> </body> </html>
5.在OWIN啓動類中添加集線器的映射,並添加要後臺運行的方法
public class Startup { private readonly string HangFireDB = @"Server=localhost;Database=ChanBanda_CollegeDB;Uid=cybd;Pwd=cybd2015;"; public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage(HangFireDB); app.UseHangfireDashboard(); app.UseHangfireServer(); app.MapSignalR(); RecurringJob.AddOrUpdate(() => PublishMessage(), Cron.Minutely());//每分鐘執行一次任務 } public void PublishMessage() { //模擬任務的代碼 GlobalHost.ConnectionManager.GetHubContext<MessageHub>().Clients.All.updateInfo(); } }
6.運行頁面,這樣頁面就會每分鐘收到服務端推送來的消息了。javascript