Update task.js

This commit is contained in:
Namhyeon Go 2021-07-16 20:10:27 +09:00 committed by GitHub
parent 3cc3f8b77b
commit 1e3b0dc47e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -17,18 +17,22 @@
*/
var Task = function(f, params) {
var now = new Date();
this.f = f;
this.params = params;
this.nextTask = null;
this.when = now.getTime();
this.when = 0;
this.delay = 0;
this.setNextTask = function(task) {
this.nextTask = task;
};
this.setWhen = function(when) {
this.when = when;
return this;
};
this.setDelay = function(delay) {
this.delay = delay;
return this;
};
};
@ -36,14 +40,19 @@ var TaskQueue = function() {
this._task = null;
this._keepalive = true;
this.queue = [];
this.put = function(task) {
this.put = function(task, delay) {
var now = new Date();
try {
task.setWhen(now.getTime());
if (typeof(delay) !== "undefined") {
task.setDelay(delay);
}
this._task = task;
this.queue.push(this._task);
this.queue.push(task);
} catch(e) {
console.error("TaskQueue.put exception: " + e.message);
}
return this;
};
this.get = function() {
@ -53,17 +62,18 @@ var TaskQueue = function() {
try {
if (this.queue.length > 0) {
var delta = this.queue.map(function(task) {
return task.when - now.getTime();
return task.when + task.delay - now.getTime();
});
var i = delta.indexOf(Math.min.apply(Math, delta));
if (i > -1) {
var d = this.queue[i].when + this.queue[i].delay - now.getTime();
if (i > -1 && d <= 0) {
task = this.queue.splice(i, 1)[0];
}
}
} catch(e) {
console.error("TaskQueue.get: " + e.message);
}
return task;
};
this.next = function() {
@ -76,12 +86,11 @@ var TaskQueue = function() {
try {
result = task.f.apply(null, [task].concat(task.params));
if (task.nextTask != null) {
this.put(task.nextTask);
this.put(task.nextTask, task.nextTask.delay);
}
} catch (e) {
console.error("Task exception: " + e.message);
console.error("task.f: " + typeof(task.f));
//WScript.echo(task.f);
console.error("task.params: " + typeof(task.params));
}
}
@ -91,13 +100,17 @@ var TaskQueue = function() {
return result;
};
this.then = function(task) {
this.then = function(task, delay) {
try {
if (typeof(delay) !== "undefined") {
task.setDelay(delay);
}
this._task.setNextTask(task);
this._task = task;
return this;
} catch(e) {
console.error("TaskQueue.then: " + e.message);
console.error(this._task);
}
};
this.run = function() {
@ -125,10 +138,10 @@ exports.createTask = function(f, params) {
}
};
exports.putTask = function(q, task) {
exports.putTask = function(q, task, delay) {
try {
if (q instanceof TaskQueue && task instanceof Task) {
return q.put(task);
return q.put(task, delay);
}
} catch(e) {
console.error("putTask exception: " + e.message);
@ -151,6 +164,6 @@ exports.stop = function(q) {
q.stop();
};
exports.VERSIONINFO = "Task Module (task.js) version 0.1";
exports.VERSIONINFO = "Task Module (task.js) version 0.2";
exports.global = global;
exports.require = require;