Using the CronScheduler
The CronScheduler is the central service provided by the DomusJS Cron Module that allows you to register and manage scheduled jobs.
It integrates seamlessly with the tsyringe dependency injection container, making it easy to plug into your application.
🔨 Example: Basic CronScheduler Usage
Section titled “🔨 Example: Basic CronScheduler Usage”import { container } from 'tsyringe';import { CronScheduler } from '@domusjs/cron';
const scheduler = container.resolve<CronScheduler>('CronScheduler');
scheduler.register({ name: 'simple-log-task', schedule: '*/5 * * * *', // Every 5 minutes task: async () => { console.log('Running scheduled task...'); },});
✅ This registers a basic cron job that logs a message every 5 minutes.
Example: Registering a Job from a Bounded Context
Section titled “Example: Registering a Job from a Bounded Context”Each bounded context should ideally register only its own cron jobs, keeping responsibilities modular and clean.
import { container } from 'tsyringe';import { CronScheduler } from '@domusjs/cron';import { CommandBus } from '@domusjs/core';import { GenerateDailyReportCommand } from './commands/generate-daily-report.command';
export function registerReportCronJobs() { const scheduler = container.resolve<CronScheduler>('CronScheduler');
scheduler.register({ name: 'generate-daily-report', schedule: '0 3 * * *', // Every day at 3:00 AM task: async () => { const commandBus = container.resolve<CommandBus>('CommandBus'); await commandBus.dispatch(new GenerateDailyReportCommand()); }, });}
✅ This approach lets the Reports Context handle its own job registration without mixing it into other modules.
Initialization Order (IMPORTANT)
Section titled “Initialization Order (IMPORTANT)”To ensure that all jobs are properly registered and the scheduler starts correctly, follow this order:
import { registerCronModule, startSchedulers } from '@domusjs/cron';
// 1️⃣ Register the cron module itselfregisterCronModule();
// 2️⃣ Register cron jobs per bounded contextregisterReportCronJobs();registerSessionCronJobs();registerCleanupCronJobs();
// 3️⃣ Start the scheduler AFTER all jobs are registeredawait startSchedulers();
✅ Order matters — if you start the scheduler before registering the jobs, they will not be picked up.
Best Practices
Section titled “Best Practices”✅ Keep cron job logic minimal — delegate heavy work to the Command Bus or Jobs module.
✅ Register context-specific jobs only where they belong.
✅ Make sure all jobs are registered before calling startSchedulers()
.