Node.js + libmysql-client + pingSync + setInterval = headache(true);

我经历了一个让我疯狂的行为,我无法解决这个问题。

我有一个脚本,打开几个MySQL连接,并将它们存储在一个数组中。 为了防止MySQLclosures未使用的连接(这个过程应该是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 --------------------------------------------------------- --------------------------------------------------------- 

它看起来像我的函数 – 或者,我的函数的一部分 – 按随机顺序执行两次。

有没有人有一个想法可能会导致这种行为? 或者有什么build议如何找出这个烂摊子的原因? 有时我得到上面引用的预期结果…但是大多数时候我得到的结果好坏参半。

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

我曾经体验过,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(); 

试着做,看看是否有帮助。