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

How to display scheduled event to the clients using SignalR background continuation process?

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

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

我在 Internet 上看过很多 SignalR 示例,但所有这些示例都使用了按钮单击事件或其他事件。在我的情况下,没有按钮单击事件,SignalR 应该继续查看数据库,然后在满足条件时通知 Event。

请做有需要的

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

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里给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>