节点进程在后续请求中找不到setTimeout对象 [英] node process can not find setTimeout object in subsequent requests

查看:50
本文介绍了节点进程在后续请求中找不到setTimeout对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在后续请求(使用express)中通过节点进程使用setTimeout方法清除超时设置.因此,基本上,我设置了直播事件开始时的超时(通过webhook通知),并旨在在一小时后为来宾用户停止该超时.正在通过setTimeout计算一小时,到目前为止效果很好.但是,如果事件在一小时前停止,我需要清除超时.我正在尝试使用clearTimeOut,但找不到相同的变量.

I am trying to clear timeout set using setTimeout method by node process, in subsequent requests (using express). So, basically, I set timeout when our live stream event starts (get notified by webhook) and aim to stop this for guest users after one hour. One hour is being calculated via setTimeout, which works fine so far. However, if event gets stopped before one hour, I need to clear the timeout. I am trying to use clearTimeOut but it just can't find same variable.

// Event starts
var setTimeoutIds              = {};    
  var val  = req.body.eventId;
  setTimeoutIds[val] =  setTimeout(function() {

        req.app.io.emit('disable_for_guest',req.body);                                
        live_events.update({event_id:req.body.eventId},{guest_visibility:false},function(err,data){
                                            //All ok
         });
     }, disable_after_milliseconds);
     console.log(setTimeoutIds);                                        
     req.app.io.emit('session_started',req.body);

When event ends:
 try{
           var event_id = req.body.eventId;
           clearTimeout(setTimeoutIds[event_id]);
           delete setTimeoutIds[event_id];
      }catch(e){
           console.log('Event ID could not be removed' + e);
      }
 req.app.io.emit('event_ended',req.body);

输出:

输出

推荐答案

您正在处理程序范围内定义 setTimeoutIds .您必须在模块级别定义它.

You are defining setTimeoutIds in the scope of the handler. You must define it at module level.

var setTimeoutIds = {};    

router.post('/webhook', function(req, res) {
     ...

这将使变量在下一次重新启动服务器之前可用.

That makes the variable available until the next restart of the server.

注意:这种方法仅在只有一台服务器且具有单个节点进程为您的应用程序提供服务的情况下有效.一旦进入多进程和/或多服务器,就需要一种完全不同的方法.

Note: this approach only works as long as you only have a single server with a single node process serving your application. Once you go multi-process and/or multi-server, you need a completely different approach.

这篇关于节点进程在后续请求中找不到setTimeout对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆