Last active
September 25, 2022 16:28
-
-
Save Ivannnnn/7f1acd52d1456bc457ff64aef6eb6eea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require("path"); | |
const exec = (command, options = {}) => | |
require("child_process").execSync(command, { encoding: "utf-8", ...options }); | |
const crontabRead = () => exec("crontab -l").trim(); | |
const crontabWrite = (str) => exec(`echo "${str}" | crontab`); | |
function parseCrontab() { | |
return crontabRead() | |
.split("\n") | |
.map((content) => ({ | |
content, | |
name: content.match(/#@(.+)@$/)?.[1] || null, | |
})); | |
} | |
const crontabEditor = (root) => { | |
function remove(name) { | |
const newCrontab = parseCrontab() | |
.filter((l) => l.name !== name) | |
.map((a) => a.content) | |
.join("\n"); | |
crontabWrite(newCrontab); | |
} | |
function write(obj) { | |
const toWriteByName = {}; | |
for (let name in obj) { | |
const { when, file, which = "node", log = null } = obj[name]; | |
toWriteByName[name] = | |
[ | |
when.join(" "), | |
"export NODE_PATH=$(npm root --quiet --location=global) &&", | |
`$(which ${which})`, | |
path.resolve(root + "/" + file), | |
log ? `>> ${path.resolve(root + "/" + log)} 2>&1` : null, | |
] | |
.filter(Boolean) | |
.join(" ") + ` #@${name}@`; | |
} | |
const replaced = parseCrontab().map(({ content, name }) => { | |
if (name in toWriteByName) { | |
content = toWriteByName[name]; | |
delete toWriteByName[name]; | |
} | |
return content; | |
}); | |
crontabWrite(replaced.concat(Object.values(toWriteByName)).join("\n")); | |
} | |
return { write, remove }; | |
}; | |
/* USAGE: | |
crontabEditor(__dirname).write({ // set root | |
'run': { // name of cronjob; overwrites if exists | |
when: ['*', '*', '*', '*', '*'], // minute, hour, ... | |
file: 'run.js', // file to be executed, relative path | |
which: 'node', // execution environment; optional, default is node | |
log: '.logs/run', // cronjob log file; optional | |
} | |
}) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment