Home > database >  Node js how to schedule jobs (non-blocking)
Node js how to schedule jobs (non-blocking)

Time:12-11

I want to schedule jobs to run every x seconds so how can it be done. An example is to ping a server every 10 seconds but all this should be async so non of the other functionality stops.

CodePudding user response:

It depends upon what you mean by "none of the other functionality stops". Pinging a server is already, non-blocking and asynchronous as all networking in nodejs is that way.

So, code like this:

setInterval(() => {
    // put code to do the ping here
}, 5000);

Will not block the rest of your server because code do to a ping is already non-blocking.

However, the rest of your server could block the setInterval() from firing on time. If you were executing some long running blocking code in your server, then the setInterval() timer callback would not happen until that code was done and it might be delayed from exactly when it was scheduled to run. Since nodejs is single threaded and event-driven, it can't process the next timer event until the previous event (whatever that was) is done executing the blocking portion of its code.

If you wanted to make absolutely sure that your timer would always run very close to when it should run, you either have to make sure the rest of your program never blocks for very long or you will need to move the timer out into another Javascript thread or process and communicate back to the main thread via messaging.

You could use a WorkerThread within your existing nodejs process or you can use the child_process module to run a separate child program that does your pinging for you. Nodejs has built-in messages that will work from either the WorkerThread or the child_process back to or from your main program.

CodePudding user response:

You would need to utilize multithreading to make non blocking code. I would suggest using the built in node.js multithreading package named worker_threads. https://nodejs.org/api/worker_threads.html

  • Related