我需要使用setInterval
每隔N秒向数据库进行查询,并将结果发送给所有的Socket.IO
客户端,所以我会这样做:
let interval_id = null
io.on('connection', function(socket) {
if (interval_id == null) {
interval_id = setInterval(function() {
db.table.items.getAll().then(function(items) {
process.emit('items_found', items)
}).catch(function(err) {
log.error(err)
})
}, config.scan.interval)
}
process.on('alarms_found', function(alarms) {
console.log(alarms.length)
})
})
它运行得很好,但我是NodeJS
的新手,不知道其他做法...一般来说,我明白使用全局范围不是最好的选择,但我不知道其他方法...
if
语句来确保setInterval
函数只运行一次。 - Kiril