Browse Source

task scan and add done

master
filesite 1 year ago
parent
commit
e5755c22be
  1. 61
      lib/taskMoniter.mjs

61
lib/taskMoniter.mjs

@ -7,6 +7,7 @@ @@ -7,6 +7,7 @@
*/
import common from './common.mjs';
import fs from 'node:fs';
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
import cron from 'node-cron';
@ -25,10 +26,17 @@ class TaskMoniter { @@ -25,10 +26,17 @@ class TaskMoniter {
done: 0, //已完成的任务数
failed: 0 //执行失败的任务数
};
}
async getStatus() {
this.statusCode = {
waiting: 'waiting',
running: 'running',
done: 'done',
failed: 'failed',
};
}
getStatus() {
return this.taskStatus;
}
async getNewTask() {
@ -43,21 +51,61 @@ class TaskMoniter { @@ -43,21 +51,61 @@ class TaskMoniter {
}
async parseTaskFile(filename, filepath) {
let task = {};
try {
task.id = filename.replace('.task', '');
task.status = this.statusCode.waiting;
task.url = await readFile(filepath, { encoding: 'utf8' });
if (task.url) {
task.url = task.url.replace(/[\r\n]/g, '');
}
}catch(error) {
console.error('Get task file content failed: %s', error);
}
return task;
}
addTask(task) {
if (typeof(this.tasks[task.id]) != 'undefined') {
return false;
}
this.tasks[task.id] = task;
this.taskStatus[task.status] ++;
this.taskStatus.total ++;
//console.log('Task added', task);
return true;
}
async checkTasks() {
if (this.checking == true) {
return;
}
try {
console.log('[%s] TaskMoniter auto check...', common.getTimeString());
this.checking = true;
//do something
console.log('[%s] TaskMoniter auto check...', common.getTimeString());
const dirPath = path.resolve(this.task_dir);
const files = await readdir(dirPath);
let task = null;
for (const file of files) {
if (file.indexOf('.task') === -1) {continue;} //ignore not *.task files
task = await this.parseTaskFile(file, `${dirPath}/${file}`);
this.addTask(task);
}
this.checking = false;
}catch(error) {
this.checking = false;
console.error('Check tasks failed: %s', error);
}
}
@ -67,8 +115,9 @@ class TaskMoniter { @@ -67,8 +115,9 @@ class TaskMoniter {
//auto run
const _self = this;
const task_check_time = this.check_time_gap;
const task_auto_run = cron.schedule(`*/${task_check_time} * * * * *`, () => {
_self.checkTasks();
const task_auto_run = cron.schedule(`*/${task_check_time} * * * * *`, async () => {
await _self.checkTasks();
console.log('Status', _self.getStatus());
}, {
scheduled: false
});

Loading…
Cancel
Save