防止NodeJS程序退出 [英] prevent NodeJS program from exiting

查看:862
本文介绍了防止NodeJS程序退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建基于NodeJS的爬虫,该爬虫正在与node-cron软件包一起使用,并且我需要防止退出脚本退出,因为应用程序应永久作为cron运行,并将在某些时段执行带有日志的爬虫.

I am creating NodeJS based crawler, which is working with node-cron package and I need to prevent entry script from exiting since application should run forever as cron and will execute crawlers at certain periods with logs.

在Web应用程序中,服务器将侦听并阻止终止,但是在无服务器应用程序中,它将在所有代码执行完毕后退出程序,而不会等待cron.

In the web application, server will listen and will prevent from terminating, but in serverless apps, it will exit the program after all code is executed and won't wait for crons.

我应该为此编写while(true)循环吗? 为此,节点中的最佳做法是什么?

Should I write while(true) loop for that? What is best practices in node for this purpose?

提前谢谢!

推荐答案

因为nodejs是单线程,所以while(true)将不起作用.它只会抢夺整个CPU,其他任何东西都无法运行.

Because nodejs is single thread a while(true) will not work. It will just grab the whole CPU and nothing else can ever run.

nodejs将在任何可能在未来运行的活动中继续运行.这包括打开的TCP套接字,侦听服务器,计时器等...

nodejs will stay running when anything is alive that could run in the future. This includes open TCP sockets, listening servers, timers, etc...

要更具体地回答,我们需要查看您的代码并查看它如何使用node-cron,但是您可以通过添加一个简单的setInterval()来保持nodejs进程的运行,例如:

To answer more specifically, we need to see your code and see how it is using node-cron, but you could keep your nodejs process running by just adding a simple setInterval() such as this:

setInterval(function() {
    console.log("timer that keeps nodejs processing running");
}, 1000 * 60 * 60);

但是,node-cron本身使用计时器,因此看来,如果您正确使用了node-cron并正确计划了将来要运行的任务,则您的nodejs进程不应停止.因此,我怀疑您的真正问题是您没有正确地使用node-cron为将来安排任务.仅当您向我们展示使用node-cron的实际代码时,我们才能为您解决该问题.

But, node-cron itself uses timers so it appears that if you are using node-cron properly and you correctly have tasks scheduled to run in the future, then your nodejs process should not stop. So, I suspect that your real problem is that you aren't correctly scheduling a task for the future with node-cron. We could help you with that issue only if you show us your actual code that uses node-cron.

这篇关于防止NodeJS程序退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆