5

我经历过一种让我发疯的行为,我无法解决它。

我有一个脚本可以打开几个 mysql 连接并将它们存储在一个数组中。为了防止 MySQL 关闭未使用的连接(该进程应该 24/7 运行),我使用 setInterval 频繁触发 pingSync()。这种方法在另一个项目中为我工作了好几个月,但在节点为 0.8.14 的新主机上,这种行为很奇怪。

setInterval(function () {
var count = 0;
console.log('---------------------------------------------------------');
console.log('Length: ');
console.log(connections.length);
connections.forEach(function(connection){
    var res = connection.pingSync();
    console.log('PING mysql '+count+ ' / '+(new Date().getTime()));
    console.log(res);
    count++;
});
console.log('---------------------------------------------------------');
}, 50000);

预期结果:

---------------------------------------------------------
Length:
4
PING mysql 0 / 1351603868929
true
PING mysql 1 / 1351603868929
true
PING mysql 2 / 1351603868929
true
PING mysql 3 / 1351603868929
true
---------------------------------------------------------

我得到的结果:

#1

---------------------------------------------------------
Length:
4
PING mysql 0 / 1351603868929
true
4
PING mysql 0 / 1351603868929
true
PING mysql 1 / 1351603868929
true
PING mysql 2 / 1351603868929
true
PING mysql 3 / 1351603868929
true
---------------------------------------------------------

#2

---------------------------------------------------------
Length:
4
PING mysql 0 / 1351604113400
4
PING mysql 0 / 1351604113400
PING mysql 1 / 1351604113400
PING mysql 2 / 1351604113400
PING mysql 3 / 1351604113400
---------------------------------------------------------
PING mysql 2 / 1351604113400
PING mysql 3 / 1351604113400
---------------------------------------------------------
---------------------------------------------------------

看起来我的函数 - 或者我的部分函数 - 以随机顺序执行两次。

有谁知道什么可能导致这种行为?或者有什么建议如何找出造成这种混乱的原因?有时我会得到上面引用的预期结果……但大多数时候我得到的结果好坏参半。

编辑: setInterval() 函数只调用一次!(我已经检查了几十次)

4

1 回答 1

0

我过去曾经历过 setInterval 有时会以意想不到的方式执行某些事情。例如,如果函数运行时间超过设置的 setInterval。一个简单的解决方法是改用 setTimeout 并在函数结束时再次设置它。

var pingMysql = function () {
  var count = 0;

  console.log('---------------------------------------------------------');
  console.log('Length: ');
  console.log(connections.length);

  connections.forEach(function(connection){
    var res = connection.pingSync();

    console.log('PING mysql '+count+ ' / '+(new Date().getTime()));
    console.log(res);

    count++;
  });

  console.log('---------------------------------------------------------');
  setTimeout(pingMysql, 50000)
};

pingMysql();

尝试这样做,看看是否有帮助。

于 2013-02-05T11:45:01.740 回答