ffffng/server/jobs/scheduler.js

100 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
2018-12-17 22:49:54 +01:00
const _ = require('lodash');
const cron = require('node-cron');
const glob = require('glob');
const moment = require('moment');
2018-12-17 22:49:54 +01:00
const config = require('../config').config
const Logger = require('../logger')
const jobFiles = glob.sync(__dirname + '/*Job.js');
_.each(jobFiles, function (jobFile) {
require(jobFile);
});
2018-12-17 22:49:54 +01:00
const tasks = {};
2018-12-17 22:49:54 +01:00
let taskId = 1;
function nextTaskId() {
const id = taskId;
taskId += 1;
return id;
}
2018-12-17 22:49:54 +01:00
function schedule(expr, jobName) {
Logger.tag('jobs').info('Scheduling job: %s %s', expr, jobName);
2018-12-17 22:49:54 +01:00
var job = require(`../jobs/${jobName}`);
2016-05-24 16:40:57 +02:00
2018-12-17 22:49:54 +01:00
if (!_.isFunction(job.run)) {
throw new Error('The job ' + jobName + ' does not provide a "run" function.');
}
2018-12-17 22:49:54 +01:00
var id = nextTaskId();
var task = {
id: id,
name: jobName,
description: job.description,
schedule: expr,
job: job,
runningSince: false,
lastRunStarted: false,
lastRunDuration: null,
state: 'idle',
enabled: true
};
2018-12-17 22:49:54 +01:00
task.run = function () {
if (task.runningSince || !task.enabled) {
// job is still running, skip execution
return;
}
2018-12-17 22:49:54 +01:00
task.runningSince = moment();
task.lastRunStarted = task.runningSince;
task.state = 'running';
2018-12-17 22:49:54 +01:00
job.run(function () {
var now = moment();
var duration = now.diff(task.runningSince);
Logger.tag('jobs').profile('[%sms]\t%s', duration, task.name);
2018-12-17 22:49:54 +01:00
task.runningSince = false;
task.lastRunDuration = duration;
task.state = 'idle';
});
};
2018-12-17 22:49:54 +01:00
cron.schedule(expr, task.run);
2018-12-17 22:49:54 +01:00
tasks['' + id] = task;
}
2018-12-17 22:49:54 +01:00
module.exports = {
init: function () {
Logger.tag('jobs').info('Scheduling background jobs...');
2016-05-24 16:40:57 +02:00
2018-12-17 22:49:54 +01:00
try {
schedule('0 */1 * * * *', 'MailQueueJob');
schedule('15 */1 * * * *', 'FixNodeFilenamesJob');
2016-05-24 19:14:09 +02:00
2018-12-17 22:49:54 +01:00
if (config.client.monitoring.enabled) {
schedule('30 */15 * * * *', 'NodeInformationRetrievalJob');
schedule('45 */5 * * * *', 'MonitoringMailsSendingJob');
schedule('0 0 3 * * *', 'OfflineNodesDeletionJob'); // every night at 3:00
2016-05-24 16:40:57 +02:00
}
2018-12-17 22:49:54 +01:00
}
catch (error) {
Logger.tag('jobs').error('Error during scheduling of background jobs:', error);
throw error;
}
2016-05-24 16:40:57 +02:00
2018-12-17 22:49:54 +01:00
Logger.tag('jobs').info('Scheduling of background jobs done.');
},
2018-12-17 22:49:54 +01:00
getTasks: function () {
return tasks;
}
}