脚本无法正常终止

脚本无法正常终止

本文介绍了Mongoose 脚本无法正常终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 node.js 脚本,我想定期运行它,它使用 mongoose 写入 mongodb.它连接到 mongodb,写入并断开连接.问题是脚本有时似乎挂起.我必须手动终止脚本(ctrl+C).

I have a node.js script that I want to run periodically that writes to mongodb using mongoose. It connects to mongodb, writes, and disconnects. The problem is that the script seems to hang sometimes. I have to manually terminate the script (ctrl+C).

mongoose.connect(MONGODB_URL);

var db = mongoose.connection;
db.on('error', function(err) {
    console.log(err);
});
db.on('open', function() {
    console.log('opened');
});
db.on('close', function() {
    console.log('closed');
});

Model.update(....., function(err) {
    if (err) throw err;
    mongoose.disconnect();
});

一切似乎都很好.该脚本打印 openedclosed 并正确更新数据库,但之后不会终止.在完成对数据库的所有更新后,我还在标注内部断开连接,因此不应该有任何会阻止脚本终止的未决查询.

Everything seems to be fine. The script prints opened and closed and updates the database correctly, but doesn't terminate after that. I also disconnect inside the callout after all updates to the database are done so there shouldn't be any pending queries that would prevent the script from terminating.

这里问了一个类似的问题:一旦你正确关闭猫鼬的连接完成但看起来没有任何真正的解决方案.

A similar question was asked here: Properly close mongoose's connection once you're doneBut it doesn't look like there were any true solutions.


我可以通过在最后添加 process.exit() 来终止它,但事实并非如此.


I can get it to terminate by adding process.exit() at the end, but that shouldn't be the case.

推荐答案

所以我发现了问题所在.作为 cron 作业,我每 15 分钟运行一次这个脚本.它在运行我们拥有的 API 的同一台服务器上运行.还有一些每 15 分钟运行一次的东西会用请求来冲击 API.不知何故,这导致脚本在连接和断开 mongodb 时出现问题.

So I found out what the issue was. I was running this script every 15 minutes as a cron job. It was running on the same server that was running an API we had. There was something else that was running every 15 minutes that would hammer the API with requests. Somehow, this caused problems with the script when connecting and disconnecting from mongodb.

我通过在不同时间运行 cron 作业解决了这个问题.我不知道有没有人可以做些什么来使 mongodb 驱动程序更健壮...

I solved the issue by running the cron job at different times. I don't know if there's anything anyone can do about it to make the mongodb drivers more robust...

这篇关于Mongoose 脚本无法正常终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:58