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.
Asked
Active
Viewed 4,407 times
11

Paul Sweatte
- 24,148
- 7
- 127
- 265

Sanket
- 945
- 11
- 24
-
A code example would help. – tikider Sep 30 '14 at 08:46
-
Added example please check it. – Sanket Sep 30 '14 at 11:14
-
Why would you need to do this? – neelsg Sep 30 '14 at 11:33
-
@neelsg: https://en.wikipedia.org/wiki/Dynamic_priority_scheduling is a well-known problem with lots of applications – Bergi Sep 30 '14 at 12:13
-
Actually in my application multiple functions' are executing parallelly i.e in a event loop. So if there are some important high priority functions are there so I want these functions to be executed first and then other. – Sanket Sep 30 '14 at 12:34
-
@Bergi I'm aware that this is a well known problem, but don't think it is possible to do in Node.js. Sometimes you can avoid such issues by re-factoring a problem. If the asker has some specific reason why he/she needs to do this, we may be able to suggest a different approach. – neelsg Sep 30 '14 at 12:39
-
@Sanket Could it be possible for you to move the high priority functions to a dedicated **[Child Process](http://nodejs.org/api/child_process.html)**? – neelsg Sep 30 '14 at 12:41
-
No if I did so then it will giving problem in a database CURD operations. – Sanket Sep 30 '14 at 12:43
-
@neelsg: Well, you can always write your own scheduler :-) With generators/continuations this should be quite possible. – Bergi Sep 30 '14 at 12:54
2 Answers
2
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.

Grigorii Chudnov
- 3,046
- 1
- 25
- 23