Execute a computing-intensive task in background

后端 未结 2 1509
遇见更好的自我
遇见更好的自我 2021-01-25 00:49

I have a task that requires a lot of computing without IO while executing and I don\'t want to block thread while executing this task. How can I do this in Node.js

2条回答
  •  [愿得一人]
    2021-01-25 01:05

    You need background workers and some kind of communication protocol between your web instance and worker instances. For example you can use kue to create tasks queue

    // web worker
    var kue = require('kue');
    var queue = kue.createQueue();
    
    ....
    
    app.post('/calculateSomeCrazyStuff', (req, res, err) => {
      queue.create('myLongRunningJobName1', {
        fibonacciSequence: 52
      }).save((err) => {
        if (err) {
          return next(err);
        }
        res.status(204).send();
      });
    });
    
    
    
    // jobs worker
    var kue = require('kue');
    var queue = kue.createQueue();
    
    
    queue.process('myLongRunningJobName1', function(job, done) {
      // calculate fibonacci
      done();
    });
    

提交回复
热议问题