shell script scheduler

This commit is contained in:
Jan Prochazka
2020-12-03 18:43:02 +01:00
parent 8d9cb51baa
commit 56eecb0836
7 changed files with 82 additions and 5 deletions

View File

@@ -2,6 +2,7 @@ const fs = require('fs-extra');
const path = require('path');
const { filesdir } = require('../utility/directories');
const socket = require('../utility/socket');
const scheduler = require('./scheduler');
function serialize(format, data) {
if (format == 'text') return data;
@@ -44,5 +45,8 @@ module.exports = {
}
await fs.writeFile(path.join(dir, file), serialize(format, data));
socket.emitChanged(`files-changed-${folder}`);
if (folder == 'shell') {
scheduler.reload();
}
},
};

View File

@@ -0,0 +1,41 @@
const { filesdir } = require('../utility/directories');
const fs = require('fs-extra');
const path = require('path');
const cron = require('node-cron');
const runners = require('./runners');
const scheduleRegex = /\s*\/\/\s*@schedule\s+([^\n]+)\n/;
module.exports = {
tasks: [],
async unload() {
this.tasks.forEach((x) => x.destroy());
this.tasks = [];
},
async processFile(file) {
const text = await fs.readFile(file, { encoding: 'utf-8' });
const match = text.match(scheduleRegex);
if (!match) return;
const pattern = match[1];
if (!cron.validate(pattern)) return;
console.log(`Schedule script ${file} with pattern ${pattern}`);
const task = cron.schedule(pattern, () => runners.start({ script: text }));
this.tasks.push(task);
},
async reload() {
const shellDir = path.join(filesdir(), 'shell');
await this.unload();
if (!(await fs.exists(shellDir))) return;
const files = await fs.readdir(shellDir);
for (const file of files) {
await this.processFile(path.join(shellDir, file));
}
},
async _init() {
this.reload();
},
};

View File

@@ -24,6 +24,7 @@ const archive = require('./controllers/archive');
const uploads = require('./controllers/uploads');
const plugins = require('./controllers/plugins');
const files = require('./controllers/files');
const scheduler = require('./controllers/scheduler');
const { rundir } = require('./utility/directories');
@@ -69,6 +70,7 @@ function start(argument = null) {
useController(app, '/uploads', uploads);
useController(app, '/plugins', plugins);
useController(app, '/files', files);
useController(app, '/scheduler', scheduler);
if (process.env.PAGES_DIRECTORY) {
app.use('/pages', express.static(process.env.PAGES_DIRECTORY));