简体   繁体   中英

How can I track “online” statuses of users if a server crashes?

I have multiple heroku dynos and a chat app. When a user logs in, their status is set to "online" in MongoDB. However, if a server crashes, their status will still be set as online. How can I update the user status to be "offline" when a server crashes?

If I only had one dyno, this would be easy. I'd just update every user to be "offline" when the server starts. Unfortunately, this is not possible with multiple servers.

As per our chat and comments.

The best option is to go with checking against last activity. So seeing when the last message was sent and if it happened within the last let's say 5 minutes they are online if there were no activity mark them as offline.

Like I mentioned in the comments, if you are not storing a date_created on the messages documents you will not have to change anything because _id stores the timestamp

ObjectId("507f191e810c19729de860ea").getTimestamp()

that returns this Date object

ISODate("2012-10-17T20:46:22Z")

This answer is another option (if you are wanting to keep them as online even if they are not sending messages):

If you would like to know they are still active even when they're not jumping from page to page, include a bit of javascript to ping your server every 60 seconds or so to let you know they are still alive. It'll work the same way as my original suggestion, but it will update your records without requiring them to be frantically browsing your site at least once every five minutes.

var stillAlive = setInterval(function () {
    /* XHR back to server
       Example uses jQuery */
    $.get("stillAlive.php");
}, 60000);

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