Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign priority to nodejs tasks in a event loop

Is there any way by which one can apply priority to Node.js task's in a event loop. I want to assign priority to task which are present in a event loop of nodejs.
Suppose in a event loop there are 5 jobs A,B,C,D,E which having same priority and then next job is received whose priority is higher than last five jobs. Then event loop starts executing that higher priority job.

like image 748
Sanket Avatar asked Sep 30 '14 07:09

Sanket


2 Answers

The event loop in node.js does not support priorities. See some documentation:

  • http://nodejs.org/api/events.html
  • http://strongloop.com/strongblog/node-js-event-loop/

Short of rewriting it, I don't think there is much you can do about that.

like image 93
neelsg Avatar answered Nov 09 '22 16:11

neelsg


You should use a priority queue, something like priorityqueuejs

In this way you can dequeue an item with the max priority and execute it.

Some code:

'use strict';

var PriorityQueue = require('priorityqueuejs');

var queue = new PriorityQueue(function(a, b) {
  return a.value - b.value;
});

queue.enq({ value: 10, func: function() { console.log("PRIORITY: 10"); } });
queue.enq({ value: 500, func: function() { console.log("PRIORITY: 500"); } });
queue.enq({ value: 300, func: function() { console.log("PRIORITY: 300"); } });
queue.enq({ value: 100, func: function() { console.log("PRIORITY: 100"); } });

(function executeNext() {
  if(queue.size()) {
    var next = queue.deq();
    next.func();
    if(queue.size()) {
      setTimeout(executeNext, 0);
    }
  }
})();

And the output is:

PRIORITY: 500
PRIORITY: 300
PRIORITY: 100
PRIORITY: 10

Here is the executeNext function extracts the next top-priority item and executes it.

like image 34
Grigorii Chudnov Avatar answered Nov 09 '22 14:11

Grigorii Chudnov