简体   繁体   中英

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.

I am calling the following in 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().

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?

I really don't think you need SignalR Hub for this case. You only need SignalR when you want user to receive immediate update of something. But actually the way you are doing is to send the data for every 30 minutes. If so, why don't you just make the client request the data for every 30 minutes? It should be much better.

  • You don't need to manage signalr connection id of each user.
  • You don't need any background job for it

Below is a sample code how to do it in javascript, using momentjs and localStorage:

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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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