UNPKG

adonisjs6-scheduler

Version:
72 lines (71 loc) 2.82 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { BaseCommand, flags } from '@adonisjs/core/ace'; import { spawn } from 'child_process'; import chokidar from 'chokidar'; import { Worker } from '../src/worker.js'; export default class SchedulerCommand extends BaseCommand { static commandName = 'scheduler:run'; static description = ''; static aliases = ['scheduler:work', 'schedule:work', 'schedule:run']; static options = { startApp: true, staysAlive: true, }; prepare() { this.app.terminating(async () => { if (this.worker) await this.worker.stop(); }); } async run() { if (this.watch) { return await this.runAndWatch(); } this.worker = new Worker(this.app); await this.worker.start(); } async runAndWatch() { const logger = await this.app.container.make('logger'); let child; const startProcess = () => { if (child) child.kill(); child = spawn('node', ['ace.js', 'scheduler:run'], { stdio: 'inherit' }); }; const watcher = chokidar.watch([this.app.appRoot.pathname], { //@ts-ignore ignored: (path, stats) => { if (path.includes('node_modules') || path.includes('.git') || path.includes('build')) { return true; } return stats?.isFile() && !path.endsWith('.ts') && !path.endsWith('.js'); }, persistent: true, ignoreInitial: true, }); let timeoutId; watcher.on('all', (event, path) => { if (typeof path === 'string') { logger.info(`File ${path.replace(this.app.appRoot.pathname, '')} changed (${event}), restarting...`); } clearTimeout(timeoutId); timeoutId = setTimeout(() => { startProcess(); }, 300); }); startProcess(); this.app.terminating(async () => { if (child) child.kill(); process.exit(); }); } } __decorate([ flags.boolean({ description: 'Restart the scheduler on file changes' }) ], SchedulerCommand.prototype, "watch", void 0);