node.js 对象中的setInterval

node.js setInterval in a object

我有以下代码:

var mmanager = require("./mmanager");
var { spawn } = require("child_process");

var exports = {
    interval: {},
    setup: function (n){
        if(n){
            this.n = n;
        }
    },
    continuous_scan: function (){
        console.log("Setting intervals");
        this.interval = setInterval(this.get_connections,120000); //120000 ms
        console.log("Interval:",this.interval);
        this.get_connections();
    },
    get_connections: function (){
        if(this.n){
            let py = spawn("python3",["get_connections.py"]);
            let dataString = '';
            py.stdout.on("data", (data) => {
                dataString += data;
            });
            py.stdout.on("end",() => {
                var response = JSON.parse(dataString);
                if(this.scan){
                    this.last_scan = this.scan;
                }
                this.scan = response;
                let obj = {
                    data: response,
                    n: this.n
                }
                mmanager.insert(obj,function(err,res){
                    if(err){
                        console.log("Error inserting data");
                        return;
                    }
                    console.log(res);
                    if(this.interval){   //some debug to see what happens
                        console.log(this.interval);
                    }else{
                        console.log("interval not found");
                    }
                    return;
                });

            });
            console.log("Start capturing ("+this.n+") ...");
            py.stdin.write(JSON.stringify(this.n));
            py.stdin.end();
        }
    },
    stop_scan: function (){
        if(this.interval){
            this.interval.clearInterval();
            return true;
        }else{
            return false;
        }
    }
}

module.exports = exports;

我想做的是每 2 分钟执行一次 python3 脚本并将数据插入数据库。 当我 运行 这段代码时,我得到了代码的第一次执行,但它似乎在其他代码中失败了。

我也看到在get_connections的执行中找不到区间。

输出:

Setting intervals
Interval: Timeout {
  _called: false,
  _idleTimeout: 120000,
  _idlePrev: 
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 120000,
     nextTick: false },
  _idleNext: 
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 120000,
     nextTick: false },
  _idleStart: 336,
  _onTimeout: [Function: get_connections],
  _timerArgs: undefined,
  _repeat: 120000,
  _destroyed: false,
  [Symbol(asyncId)]: 6,
  [Symbol(triggerAsyncId)]: 1 }
Start capturing (2) ...
{... 
some successful result 
...}
interval not found

2分钟后没有跟进。

不知道是区间变量的赋值问题还是node.js

的异步执行问题

我该如何解决这个问题?

当将 get_connection 作为回调传递给 setInterval 时,您丢失了对导出对象的引用,并且 this 不是导出对象而是全局对象。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).

要获得正确的 this,您可以将函数绑定到 exports 对象或在函数调用周围放置一个闭包。

this.interval = setInterval(() => this.get_connections(),120000); //120000 ms