job-manager.js 2.5 KB
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JobManager = void 0;
class JobManager {
    runningJobs;
    jobLogPath;
    constructor(jobLogPath) {
        this.jobLogPath = jobLogPath;
        this.runningJobs = new Set();
    }
    getLogFilePath(dateTime) {
    }
    getJobLoggerNamespace(handlerName, dateTime, logId) {
    }
    hasJob(jobId) {
        return this.runningJobs.has(jobId);
    }
    async runJob(jobId, jobJsonParams, logId, logDateTime, executorTimeout, handlerName, jobHandler, callback) {
        let result, timeoutTimer, error;
        const startTime = Date.now();
        try {
            if (this.hasJob(jobId)) {
                throw new Error('已有相同任务正在运行');
            }
            this.runningJobs.add(jobId);
            let jobParams = {};
            try {
                jobParams = JSON.parse(jobJsonParams) || {};
            }
            catch { }
            if (executorTimeout) {
                timeoutTimer = setTimeout(() => this.finishJob({
                    jobId,
                    logId,
                    callback,
                    timeoutTimer: null,
                    use_time: Date.now() - startTime,
                    result: null,
                    error: new Error('任务执行超时')
                }), executorTimeout * 1000);
            }
            result = await jobHandler(jobParams);
            if (result && result.error) {
                error = result.error;
                delete result.error;
                if (Object.keys(result).length === 0) {
                    result = undefined;
                }
            }
        }
        catch (err) {
            error = err;
        }
        finally {
            await this.finishJob({
                jobId,
                logId,
                callback,
                timeoutTimer,
                use_time: Date.now() - startTime,
                result,
                error
            });
        }
    }
    async readJobLog(logDateTime, logId) {
    }
    async finishJob({ jobId, logId, callback, timeoutTimer, use_time, result, error }) {
        try {
            timeoutTimer && clearTimeout(timeoutTimer);
            await callback({ error, logId, use_time, result });
        }
        catch (err) {
            console.error(`完成任务时发生错误: ${err.message}`);
        }
        finally {
            this.runningJobs.delete(jobId);
        }
    }
}
exports.JobManager = JobManager;
//# sourceMappingURL=job-manager.js.map