Prevent NodeJS program from exiting

I am creating a NodeJS based crawler that runs on a package node-cron

and I need to prevent the script from exiting as the application is supposed to run forever like cron and will execute crawlers at specific periods with logs.

In a web application, the server will listen and will prevent it from completing, but in serverless applications, it will exit the program after all the code has been executed and will not wait for crosses.

Should I write a loop while(true)

for this? What are the best practices in node for this purpose?

Thanks in advance!

+3


source to share


1 answer


Since nodejs is a single thread, a while(true)

won't work. It will simply take over the entire processor and will be unable to execute anything else.

nodejs will work when anything is live, which might work in the future. This includes open TCP sockets, listening servers, timers, etc.

To answer more accurately, we need to see your code and see how it uses node-cron, but you can keep the nodejs process simple by adding a simple setInterval()

one like:



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

      

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

+4


source







All Articles