如何使用SignalR后台延续过程向客户显示预定事件?

时间:2015-02-28 15:09:32

标签: asp.net-mvc signalr signalr-hub signalr.client

我有数据库中的事件列表。事件具有以下属性Message, UserId, StartDate, EndDate, StartTime, EndTime

我的要求是通过在网站上显示15分钟之前的事件来提醒用户。我正在使用SignalR概念实现此功能。 SignalR应该在后台处理条件,如果满足条件(在15分钟之前),它应该自动显示在相应的用户页面上。

我在互联网上看到了很多SignalR示例,但所有这些示例都使用了按钮点击事件或其他事件。在我的情况下,没有按钮点击事件,SignalR应该继续查看数据库,然后在符合条件的情况下通知Event。

请做到需要

1 个答案:

答案 0 :(得分:1)

我在回答自己的问题。它可能对其他人有帮助。 我通过使用Timer命名空间中的using System.Threading类来实现此目的。以下是我的工作代码。

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalRNotifications.Models;
using System;
using System.Threading;
using System.Linq;
using WebMatrix.WebData;


namespace SignalRNotifications
{
[HubName("processEvents")]
public class ProcessEvents : Hub
{
    UsersContext db = new UsersContext();
    public void ShowEvent(string name)
    {
        Timer _timer = new Timer(dispmsg,                
            null,
            TimeSpan.Zero,
           TimeSpan.FromSeconds(2));
    }
    public void dispmsg(object state)
    {

        var userEvents = db.MyEvents.ToList().Where(f => f.StartDateTime.AddMinutes(-15) >= DateTime.Now).ToList();
        Clients.All.BroadCastEvent("Hello Sridhar you have ("+userEvents.Count()+") Events<br/>");
    }

}
}

我只是在Index.html for client

中编写代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div id="container"></div>
</body>
<script src="/Scripts/jquery-1.7.1.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 con = $.connection.processEvents;
    con.client.broadCastEvent = function (name) {
        $("#container").append(name);

    }
    $.connection.hub.start().done(function () {
        con.server.showEvent("sridhar");
    });
});
</script>
</html>