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.
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.
Should I write while(true)
loop for that?
What is best practices in node for this purpose?
Thanks in advance!
There is no way to prevent the exiting of the event loop at this point, and once all 'exit' listeners have finished running the Node.js process will terminate.
js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.
The process. exit() method is used to end the process which is running at the same time with an exit code in NodeJS. Parameter: This function accepts single parameter as mentioned above and described below: Code: It can be either 0 or 1.
You can start a node by using the startNode command. You can stop a node by using the stopNode command.
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 will stay running when anything is alive that could run in the future. This includes open TCP sockets, listening servers, timers, etc...
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With