简体   繁体   English

ASP.NET Core MVC应用程序(带SignalR)的每个用户的周期性HangFire作业

[英]Recurring HangFire job for each user of an ASP.NET Core MVC app (w/ SignalR)

I have an ASP.NET MVC Core application with HangFire installed. 我有一个安装了HangFire的ASP.NET MVC Core应用程序。

I am calling the following in Startup.Configure: 我在Startup.Configure中调用以下命令:

RecurringJob.AddOrUpdate(() => GetCurrentUserNotifications("User1"), Cron.MinuteInterval(30));

    public void GetCurrentUserNotifications(string userId)
    {
        _connectionManager.GetHubContext<NotificationsHub>()
            .Clients.All.broadcastNotifications(_repository.GetNotifications()
            .Where(x => x.DateTime == DateTime.Now && x.CreatedBy == userId));
    }

This way everytime the job runs, it will broadcast the notifications to the currently logged in user. 这样,每次作业运行时,它将广播通知给当前登录的用户。 The goal is to check the database every 30 minutes for any notifications created by the current logged in user where the Notification DateTime is equal to DateTime.Now(). 目标是每30分钟检查数据库中是否有当前登录用户创建的任何通知(通知DateTime等于DateTime.Now())。

My concern is how I will handle when I have multiple clients at the same time. 我关心的是同时拥有多个客户时如何处理。 For example User1 is logged in and User2 is logged in. Should 2 separate Hangfire jobs be started or should I be broadcasting to SignalR differently? 例如,用户1已登录,用户2已登录。是否应该启动2个单独的Hangfire作业,还是应该以不同的方式向SignalR广播?

I really don't think you need SignalR Hub for this case. 在这种情况下,我真的不认为您需要SignalR Hub。 You only need SignalR when you want user to receive immediate update of something. 仅当您希望用户立即接收到某些内容的更新时,才需要SignalR。 But actually the way you are doing is to send the data for every 30 minutes. 但是实际上您要做的是每30分钟发送一次数据。 If so, why don't you just make the client request the data for every 30 minutes? 如果是这样,为什么不让客户每30分钟请求一次数据呢? It should be much better. 它应该好得多。

  • You don't need to manage signalr connection id of each user. 您无需管理每个用户的信号器连接ID。
  • You don't need any background job for it 您不需要任何后台工作

Below is a sample code how to do it in javascript, using momentjs and localStorage: 下面是一个示例代码,该代码示例如何使用momentjs和localStorage在javascript中进行操作:

function getData() {
    var lastRequestTimeStr = localStorage.getItem('lastRequestTime');
    if (lastRequestTimeStr) {
        var lastRequestTime = moment(lastRequestTimeStr);
        var now = moment();
        if (now.diff(lastRequestTime, 'minutes') >= 30) {
            //get data from server now  

            //save time to localStorage
            localStorage.setItem('lastRequestTime', now.format());
        }
    }
}

$(document).ready(function () {
    getData();
    setInterval(getData, 60000); //call this getData every 1 minutes to make sure we do not miss
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM