EAzevedo
EAzevedo

Reputation: 791

Nodejs setInterval to repeat a task every 30s

I built a nodejs application that should execute several tasks.

My app.js has a function call to the manager module which controls those tasks.

I want to call that function from my app.js and perform those tasks every 30s.

something like:

setInterval(manager.tasks(), 30000);

My question is that if using setInterval could give me any performance problems (slowing down the computer, blocking resources or any other reason)

Is there a more efficient way to do this or is setInterval ok?

Upvotes: 2

Views: 3792

Answers (4)

Khaled Osman
Khaled Osman

Reputation: 1477

it depends on how heavy the work/processing you want to do is, setInterval is async so your code will only be run once every 30 seconds, but at the same time JavaScript is single-threaded, so if you're doing a lot of work in your task, the one time it runs in 30 seconds it may take too long to execute thus blocking resources.

In most cases you should be fine using setInterval, but if you really want to emulate multi-threading or if you're doing too much work in your task, you may want to spawn another child process https://nodejs.org/api/child_process.html process or use the new Worker Threads API https://nodejs.org/api/worker_threads.html instead, but keep in mind its not as simple to implement as a setInterval call

Upvotes: 2

localhost
localhost

Reputation: 513

It completely depends on the function you executing inside setInterval. If it is I/O bound operation then you don't need to worry too much because libuv will handle itself But if it is CPU bound then I will suggest you to use child_process api to fork a new child process and do your stuff in to that.

Upvotes: 1

rexel
rexel

Reputation: 11

setInterval is implemented in standard node js, you won't have any performance / blocking problems, most libraries also use setInterval

Upvotes: 1

Thyagarajan C
Thyagarajan C

Reputation: 8213

Use node-cron or node-schedule instead

Upvotes: 1

Related Questions