Created
September 4, 2020 13:39
-
-
Save dreamer01/372e36b56231e1134e39a03e74db6caf to your computer and use it in GitHub Desktop.
A simple priority based task runner with a given cuncurrency for asynchronous tasks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Task Runner | |
// Implement Asynchronous Task Runner | |
// tasks execute in an order of priority | |
// If the task runner have bandwidth it will pick immediately | |
// A "TaskRunner" Constructor takes one argument, "concurrency", and exposes one method "push" on its prototype. | |
// The "push" method takes two arguments. First one is task which is a "function" & second argument priority number | |
class TaskRunner { | |
constructor(concurrency) { | |
this.concurrency = concurrency; | |
this.taskList = []; | |
} | |
// push | |
push(task, priority) { | |
if (this.taskList.length < this.concurrency) { | |
this.execute(task); | |
} else { | |
// push it into taskList | |
this.taskList.push({ id: new Date().getTime(), task, priority }); | |
} | |
} | |
// Task object id, task, priority | |
execute(task) { | |
// start timeout here no response instead of done, invoke sleep or discard | |
task(this.done); | |
} | |
logicForPriority(final, task) { | |
if (task.priority > final.priority) { | |
return task; | |
} | |
} | |
done() { | |
// next task is present | |
if (this.taskList.length > 0) { | |
// priority check | |
// sort and pick first but FIFO will be lost | |
let newTask = taskList.reduce(this.logicForPriority); | |
this.execute(newTask.task); | |
// decision to remove task from task list is upon execution not completion | |
this.taskList = this.taskList.filter((t) => t.id !== newTask.id); | |
} | |
} | |
} | |
var r = new TaskRunner(3); | |
console.log(typeof r.push); | |
// r.push(exampleSimpleTask1, 1); | |
// executes immediately 3 | |
// r.push(exampleSimpleTask2, 2); | |
// executes immediately 2 | |
// r.push(exampleSimpleTask3, 1); | |
// executes immediately 1 | |
// r.push(exampleSimpleTask4, 5); | |
// should wait until one of the running tasks completes | |
// r.push(exampleSimpleTask5, 4); | |
// should wait until one of the running tasks completes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment