Search code examples
javascriptangularjsnode.jsmongodbmeanjs

Mean.js Node.js background processes


I've got a mean.js app I'm writing and I am conceptually confused about background processes.

I need to have some processes that run continuously in the background that operate on the mongodb database and do stuff like cleanup, email, tweets, etc.

I need a lot of the same functionality and libraries I have in my web app available to these background procs.

What is the best way to do this? Do I start with a brand new source base and treat these worker procs like a separate app? Or do I create, say, a daemon folder and fork the background procs when I start the server.js with grunt?

I think I am confusing myself and probably making this more complicated than it should be. I have looked at node daemon and child_processes and simple_daemon. But I'm not sure what path to take.

Thanks for your help.


Solution

  • You can use setInterval() to run scheduled or repeating tasks within the mean.js app. Because of the way node.js works, as long as node is running your app, any callback defined to run in setInterval() or setTimeout() will run once loaded. This means you can keep your background logic inside your controllers/models or in an adjacent file. You can include your background script, e.g. require()-ing it from the main app.js file, or from anywhere within your controllers, models, etc.

    e.g.

    app.js:

    require('tasks/doStuff');
    require('express');
    
    /* express/app stuff here */
    

    tasks/doStuff.js:

    require('mongoose');
    require('some/other/stuff');
    
    setInterval( function() {
        console.log('interval happened');
    }, 1000);
    

    This approach does require some design/architectural considerations. Namely, your tasks are now tied to the successful execution of your node mean.js app. If your mean.js app crashes/dies, your tasks will have also died.