Storing the return value of node.js setTimeout in redis

后端 未结 3 1176
礼貌的吻别
礼貌的吻别 2021-02-13 09:48

I\'m using setTimeout in Node.js and it seems to behave differently from client-side setTimeout in that it returns an object instead of a number. I wan

3条回答
  •  时光说笑
    2021-02-13 10:47

    I was attempting to do the same thing as the OP. My solution was to set the timeout with a conditional check on a new key inside the timeout in my disconnect handler:

    redis.hset("userDisconnecting:" + userId, "disconnect", 1);
    
    setTimeout(function() {
        redis.hget("userDisconnecting:" + userId, "disconnect",
         function(err, result) {
            if (result.toString() === "1") {
               //do stuff, like notify other clients of the disconnect.
            }
        });
    }, 10000);
    

    Then, when the client connects again, I set that key to 0, so the stuff that needs to fire on true disconnect doesn't happen:

    redis.hset("userDisconnecting:" + userId, "disconnect", 0);
    

    The timeouts themselves aren't persistent across server restarts, but you could solve that by kicking off a sweeper method on startup. Connected clients would come back "online" pretty quickly.

提交回复
热议问题