admin管理员组文章数量:1325236
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.
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.
- A code example would help. – tikider Commented Sep 30, 2014 at 8:46
- Added example please check it. – Sanket Commented Sep 30, 2014 at 11:14
- Why would you need to do this? – neelsg Commented Sep 30, 2014 at 11:33
- @neelsg: en.wikipedia/wiki/Dynamic_priority_scheduling is a well-known problem with lots of applications – Bergi Commented Sep 30, 2014 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 Commented Sep 30, 2014 at 12:34
2 Answers
Reset to default 3The event loop in node.js does not support priorities. See some documentation:
- http://nodejs/api/events.html
- http://strongloop./strongblog/node-js-event-loop/
Short of rewriting it, I don't think there is much you can do about that.
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.
本文标签: javascriptAssign priority to nodejs tasks in a event loopStack Overflow
版权声明:本文标题:javascript - Assign priority to nodejs tasks in a event loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742166901a2425993.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论