Skip to content

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.


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.

/contexts/reports/register-cron.ts
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.


To ensure that all jobs are properly registered and the scheduler starts correctly, follow this order:

/apps/bootstrap.ts
import { registerCronModule, startSchedulers } from '@domusjs/cron';
// 1️⃣ Register the cron module itself
registerCronModule();
// 2️⃣ Register cron jobs per bounded context
registerReportCronJobs();
registerSessionCronJobs();
registerCleanupCronJobs();
// 3️⃣ Start the scheduler AFTER all jobs are registered
await startSchedulers();

Order matters — if you start the scheduler before registering the jobs, they will not be picked up.


✅ 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().