opt-cc/api/cron-job/cron.js

68 lines
2.0 KiB
JavaScript

"use strict";
const cron = require('cron');
const async = require('async');
const {exec} = require('child_process');
const UserModel = require('../models/user');
const signatureTool = require('../tools/signature-tool');
const createAllSignatures = () => {
console.log('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': cron job started - UPDATE SIGNATURES');
// mock response
const res = {
locals: {
items: {}
}
};
// re-create signature image for each active user
UserModel.find({}, (err, users) => {
async.eachSeries(users, (user, callback) => {
// mock next to execute callback
const next = (err) => {
if (!err || (err && err.message.startsWith('Fraction not defined'))) {
callback()
} else {
console.error('\x1b[41m%s\x1b[0m', new Date().toLocaleString()
+ ': Error in execution - UPDATE SIGNATURES: ' + err)
}
};
signatureTool(user._id, res, next)
}, () => {
if (err) {
console.error('\x1b[41m%s\x1b[0m', new Date().toLocaleString()
+ ': Error in execution - UPDATE SIGNATURES: ' + err)
}
console.log('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': finished successful - UPDATE SIGNATURES');
})
});
};
const createBackup = () => {
console.log('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': cron job started - CREATE BACKUP');
exec(__dirname + '/../../backup/backup.sh', (error, stdout, stderr) => {
if (error) {
console.log(error);
}
console.log('\x1b[32m%s\x1b[0m',stderr);
console.log('\x1b[35m%s\x1b[0m', new Date().toLocaleString()
+ ': cron job finished - CREATE BACKUP');
})
};
// Execute daily @ 02:30 AM
const cronJobSignature = cron.job('00 30 02 * * *', createAllSignatures);
// Execute on Mon, Thu and Sat @ 04:00 AM
const cronJobBackup = cron.job('00 00 04 * * mon,thu,sat', createBackup);
module.exports = {
cronJobSignature: cronJobSignature,
cronJobBackup: cronJobBackup,
createAllSignatures: createAllSignatures
};