Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run continuous Background Job with Node JS

Consider there is a task A and other n tasks. I wan to run a task A in parallel to other n tasks. Task A is just fetching data from queue in every 5 seconds.

I am new to Node JS. Is there any way to run this task/job A in background or is there any solution ??

like image 219
user2874299 Avatar asked Oct 13 '13 19:10

user2874299


People also ask

Is NodeJS good for CPU intensive applications?

Node. js provides developers a system with single-threaded event loop architecture that provides a non-blocking I/O mechanism. This works great until we get to CPU-intensive tasks. In this case, Node's performance isn't up to the mark.

What is process nextTick ()?

nextTick. A method of the native Node process module, process. nextTick is similar to the familiar setTimeout method in which it delays execution of its callback function until some point in the future.


1 Answers

Depends a lot on what the tasks are. If I understand your question, you can do this two ways: 1, run a function with a timer, and 2, spawn a child process.

1

function taskA(){...}

setInterval(taskA,5000);

2

//same code as 1, but in a child process
var spawn = require('child_process').spawn,
ls    = spawn('taskA.js');
//taskA.js has the code from example 1

You might prefer 2 to 1 if you are doing a lot of other things in the main process, because node is single threaded. It should also be noted that there are likely better ways to do this in certain circumstances. For example, in a cloud-based webapp, I might rely on the PAAS's services to run the background task. You also might want to look into https://github.com/nodejitsu/forever-monitor

Here's a great article on how to handle background jobs in webapps. https://devcenter.heroku.com/articles/background-jobs-queueing It isn't node specific, however. It is also specific to the Heroku platform.

like image 62
Zeke Nierenberg Avatar answered Sep 30 '22 03:09

Zeke Nierenberg