node.js setInterval在自定义模块中不起作用

我正在开发一个在node.js中的Web应用程序,使用snmp从networking上的设备收集数据。 这是我第一次真正遇到node.js和javascript。 在应用程序中,每个设备将通过一个名为SnmpMonitor.js的模块进行操作。 该模块将保持基本的设备数据以及snmp和数据库连接。

该应用程序的function之一是能够不断监测智能计量设备的数据。 为此,我创build了以下代码来启动和停止对设备的监视。 它使用setInterval来不断发送一个snmp get请求到设备。 然后,事件监听器将其采集并将收集到的数据添加到数据库中。 现在,听众只是打印,以显示它是成功的。

 var dataOIDs = ["1.3.6.1.2.1.1.1.0","1.3.6.1.2.1.1.2.0"]; var intervalDuration = 500; var monitorIntervalID; var dataCollectionEvent = "dataCollectionComplete"; var emitter = events.EventEmitter(); // Uses native Event Module //... function startMonitor(){ if(monitorIntervalID !== undefined){ console.log("Device monitor has already started"); } else { monitorIntervalID = setInterval(getSnmp,intervalDuration,dataOIDs,dataCollectionEvent); emitter.on(dataCollectionEvent,dataCallback); } } function dataCallback(recievedData){ // receivedData is returned from getSnmp completion event // TODO put data in database console.log("Event happened"); } function stopMonitor(){ if(monitorIntervalID !== undefined){ clearInterval(monitorIntervalID); emitter.removeListener(dataCollectionEvent,dataCallback); } else { console.log("Must start collecting data before it can be stopped"); } } //... 

我也有一个testing文件, test.js ,需要模块,开始监控,等待10秒,然后停止它。

 var test = require("./SnmpMonitor"); test.startMonitor(); setTimeout(test.stopMonitor,10000); 

我的问题是, startMonitor()中的setInterval函数没有运行。 我曾尝试将console.log("test"); 之前,之内,之后进行testing。 内部testing输出从不执行。 monitorIntervalIDvariables也是undefined 。 我已经testing了setInterval(function(){ console.log("test"); },500); 在我的test.js文件,它运行正常,没有问题。 我觉得这是一个noobie错误,但我似乎无法弄清楚为什么它不会执行。

这里是整个模块的链接: SnmpMonitor.js

我不确定到底发生了什么问题,但是通过检修整个class级/模块来完成工作。 我想我的方式是让我创build新的监视器对象,但我错了。 相反,我在监视器文件中创build了两个function,它们完成相同的function。 我将启动function更改为以下。

 SnmpMonitor.prototype.start = function() { var snmpSession = new SNMP(this.deviceInfo.ipaddress,this.emitter); var oids = this.deviceInfo.oids; var emit = this.emitter; var duration = this.intervalDuration; this.intervalID = setInterval(function(){ snmpSession.get(dataCollectionEvent,emit,oids); },duration); }; 

当匿名函数中设置callback函数时, setInterval函数似乎工作得最好,即使技术上可以直接传递函数。 使用this. 符号我创build了一些类/模块/函数variables(无论它在js中调用)在整个类的范围内。 由于某些原因通过this.访问variablesthis. 直接在一个函数或expression式中工作得不是那么好,所以我为它们创build了临时variables。 在我的另一个版本中,所有的variables都是全局的,js似乎并不那么喜欢。