First of all, let me say:
This is a big problem.
In general, running background tasks in a single streaming environment is problematic for obvious reasons.
Let me start from the end, your third approach.
Using the function with a timer:
Running the second function with a timer sounds good, but how do you know if the time is up?
You can do something like:
function myFunc(){ var date = Date.now(); while(date - Date.now() < 5 || nothingElseToDo()) {
However, it is not very efficient or accurate, and 5 milliseconds is a lot.
How about your second approach, flow?
Alternatively, you can use threads with threads_a_gogo, which seems to suit your use very well for creating background threads.
NOTE. This is not a viable example, threads_a_gogo does not work in node 0.10.x
They have a detailed example (I copy here) on GitHub showing how to use streams with an event emitter:
quickIntro_evented_childThreadCode.js
// This is the code that .load () ed into the child / background stream:
function fibo (n) { return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1; } thread.on('giveMeTheFibo', function onGiveMeTheFibo (data) { this.emit('theFiboIs', fibo(+data));
main file:
var thread= require('threads_a_gogo').create(); thread.load(__dirname + '/quickIntro_evented_childThreadCode.js'); //Emit 'giveMeTheFibo' in the child/background thread. thread.emit('giveMeTheFibo', 35); //Listener for the 'theFiboIs' events emitted by the child/background thread. thread.on('theFiboIs', function cb (data) { process.stdout.write(data); this.emit('giveMeTheFibo', 35); }); (function spinForever () { process.stdout.write("."); process.nextTick(spinForever); })();
This type of event emitter, while the main application captures events in a stream suitable for your use case.
What will I do:
I also wonβt write all the data that I need to crunch in the background in a parallel queue in some kind of data store (possibly redis) and perform asynchronous recording from NodeJS. Then I would read them with my "task", the code (process, yes) to complete these tasks.
Thus, it is clear that this task is not part of the normal server flow.