UNPKG

@freearhey/chronos

Version:

Node.js CLI tool for running scripts on a schedule

38 lines (27 loc) 964 B
#!/usr/bin/env node import { parseArgsStringToArgv } from 'string-argv' import { spawn } from 'node:child_process' import { Command } from 'commander' import cron from 'node-cron' const program = new Command() program .requiredOption('-e, --execute <command>', 'command to be executed') .requiredOption('-p, --pattern <pattern>', 'cron pattern') .option('-l, --log', 'enable console log') .parse(process.argv) const options = program.opts() let args = parseArgsStringToArgv(options.execute) const cmd = args.shift() let child if (options.log) process.stdout.write(`started...\r\n`) cron.schedule(options.pattern, () => run(cmd, args)).start() function run(cmd, args) { if (child) child.kill('SIGINT') if (options.log) process.stdout.write(`[${options.pattern}] ${new Date().toJSON()}`) child = spawn(cmd, args) child.stdout.pipe(process.stdout) child.stderr.pipe(process.stderr) child.on('close', () => { child = undefined }) }