今天在园子里看到一篇关于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.运行页面,这样页面就会每分钟收到服务端推送来的消息了。